用c语言实现按数值插入单链表
时间: 2023-10-24 17:07:01 浏览: 85
好的,可以教您如何用C语言实现按数值插入单链表。下面是代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
ListNode *insert(ListNode *head, int val) {
ListNode *newNode = malloc(sizeof(ListNode));
newNode->val = val;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
return head;
}
if (val < head->val) {
newNode->next = head;
head = newNode;
return head;
}
ListNode *curr = head;
while (curr->next != NULL && curr->next->val < val) {
curr = curr->next;
}
newNode->next = curr->next;
curr->next = newNode;
return head;
}
void printList(ListNode *head) {
ListNode *curr = head;
while (curr != NULL) {
printf("%d ", curr->val);
curr = curr->next;
}
printf("\n");
}
int main() {
ListNode *head = NULL;
head = insert(head, 5);
head = insert(head, 1);
head = insert(head, 3);
head = insert(head, 6);
head = insert(head, 2);
printList(head);
return 0;
}
```
在这个示例中,我们定义了一个`ListNode`结构体,并创建了一个名为`insert`的函数,用于按数值将节点插入单链表。最后我们调用`printList`函数打印链表。运行这个程序会输出:1 2 3 5 6。
阅读全文