c语言,实现一个函数,在带头结点的整数序列链表(升序)中,插入一个新函数,且新链表依然有序。
时间: 2024-12-14 22:17:25 浏览: 48
在C语言中,我们可以定义一个名为`insert_sorted_linklist`的函数,用于在升序的带头结点链表中插入一个新节点,同时保持链表的顺序。下面是一个简单的实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结点结构
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建链表头节点
Node* create_node(int value) {
Node* newNode = (Node*) malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 插入函数
Node* insert_sorted_linklist(Node* head, int value) {
Node* new_node = create_node(value);
if (head == NULL || head->data > value) {
new_node->next = head;
head = new_node;
} else {
Node* current = head;
while (current->next != NULL && current->next->data < value) {
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
return head;
}
// 打印链表
void print_list(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Node* head = create_node(1); // 假设初始链表是 [1]
head = insert_sorted_linklist(head, 3); // 插入 3 后链表变为 [1, 3]
head = insert_sorted_linklist(head, 0); // 插入 0 后链表变为 [0, 1, 3]
printf("Sorted linked list after insertions:\n");
print_list(head);
return 0;
}
```
这个代码首先定义了链表节点结构和一个辅助函数来创建新的节点。`insert_sorted_linklist`函数根据链表内容和新值的位置,正确地插入新节点。`print_list`函数用于展示链表内容。在`main`中展示了如何使用该函数。
阅读全文
相关推荐




















