1!(链表)先建立有序(从小到大)带有头节点的单向链表,再删除 个节点,并将链表输出。
时间: 2023-07-11 21:44:22 浏览: 90
链表功能有建立,排序,插入,删除,输出
好的,我来解答你的问题。
首先,我们需要定义链表节点的结构体:
```c
typedef struct Node {
int val;
struct Node *next;
} ListNode;
```
然后,我们可以编写一个函数,用于在有序链表中插入节点:
```c
ListNode* insertNode(ListNode *head, int val) {
ListNode *newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->val = val;
newNode->next = NULL;
if (head == NULL || val < head->val) {
newNode->next = head;
head = newNode;
} else {
ListNode *cur = head;
while (cur->next != NULL && cur->next->val < val) {
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
}
return head;
}
```
接下来,我们可以编写一个函数,用于删除指定节点:
```c
ListNode* deleteNode(ListNode *head, int val) {
if (head == NULL) {
return NULL;
}
if (head->val == val) {
ListNode *temp = head;
head = head->next;
free(temp);
return head;
}
ListNode *cur = head;
while (cur->next != NULL && cur->next->val != val) {
cur = cur->next;
}
if (cur->next != NULL) {
ListNode *temp = cur->next;
cur->next = cur->next->next;
free(temp);
}
return head;
}
```
最后,我们可以编写一个函数,用于输出整个链表:
```c
void printList(ListNode *head) {
ListNode *cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
```
完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node *next;
} ListNode;
ListNode* insertNode(ListNode *head, int val) {
ListNode *newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->val = val;
newNode->next = NULL;
if (head == NULL || val < head->val) {
newNode->next = head;
head = newNode;
} else {
ListNode *cur = head;
while (cur->next != NULL && cur->next->val < val) {
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
}
return head;
}
ListNode* deleteNode(ListNode *head, int val) {
if (head == NULL) {
return NULL;
}
if (head->val == val) {
ListNode *temp = head;
head = head->next;
free(temp);
return head;
}
ListNode *cur = head;
while (cur->next != NULL && cur->next->val != val) {
cur = cur->next;
}
if (cur->next != NULL) {
ListNode *temp = cur->next;
cur->next = cur->next->next;
free(temp);
}
return head;
}
void printList(ListNode *head) {
ListNode *cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
int main() {
ListNode *head = NULL;
// 插入节点
head = insertNode(head, 4);
head = insertNode(head, 2);
head = insertNode(head, 1);
head = insertNode(head, 3);
head = insertNode(head, 5);
// 输出链表
printList(head);
// 删除节点
head = deleteNode(head, 3);
// 输出链表
printList(head);
return 0;
}
```
希望能够帮到你!
阅读全文