编写在非递减有序链表中插入一个元素使链表元素仍有序的函数,并利用该函数建立一个非递减有序单向链表。
时间: 2023-04-01 10:03:03 浏览: 214
可以回答这个问题。在非递减有序链表中插入一个元素可以按照以下步骤进行:
1. 创建一个新节点,将要插入的元素存储在该节点中。
2. 遍历链表,找到第一个大于等于要插入元素的节点。
3. 将新节点插入到该节点之前。
以下是一个示例代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *insert(Node *head, int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
return newNode;
}
if (data < head->data) {
newNode->next = head;
return newNode;
}
Node *current = head;
while (current->next != NULL && current->next->data <= data) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
return head;
}
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node *head = NULL;
head = insert(head, 5);
head = insert(head, 3);
head = insert(head, 7);
head = insert(head, 1);
head = insert(head, 9);
printList(head);
return ;
}
```
输出结果为:1 3 5 7 9,即为非递减有序单向链表。
阅读全文