C++呈现对任意输入的一组数据,建立一个递增有序的单链表
时间: 2023-05-12 08:03:43 浏览: 96
好的,我可以回答这个问题。以下是建立递增有序单链表的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
void sortList(struct Node** head_ref) {
struct Node* current = (*head_ref);
struct Node* index = NULL;
int temp;
if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
index = current->next;
while (index != NULL) {
if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}
int main() {
struct Node* head = NULL;
insert(&head, 6);
insert(&head, 3);
insert(&head, 9);
insert(&head, 2);
insert(&head, 7);
printf("Original list: \n");
printList(head);
sortList(&head);
printf("\nSorted list: \n");
printList(head);
return 0;
}
```
这个程序会接收一组数据,然后将它们插入到一个单链表中,并对链表进行排序,最后输出排序后的链表。
阅读全文