#include<stdio.h>
#include<malloc.h>
typedef struct NodeList {
struct NodeList* next;
int data;
}Node;
Node* getList() {
int number, i;
Node* head = NULL;
Node* tail = NULL;
printf("请输入节点个数:");
scanf("%d", &number);
for (i = 0; i < number; i++) {
int data;
scanf("%d", &data);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->next = NULL;
newNode->data = data;
if (!head) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 冒泡排序 bubble sort
void sortList(Node* head) {
Node* move = head;
Node* tail = NULL;
while(1) {
if (move->next == tail) {
if (move == head) {
return;
} else {
tail = move;
move = head;
}
} else {
if (move->data > move->next->data) {
int data = move->data;
move->data = move->next->data;
move->next->data = data;
}
move = move->next;
}
}
}
void displayList(Node* head) {
while(head) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
Node* inserList(Node* head, Node* newNode) {
Node* move = head;
if (move->data > newNode->data) {
newNode->next = move;
return newNode;
}
while(move->next) {
if (move->data <= newNode->data && move->next->data >= newNode->data) {
newNode->next = move->next;
move->next = newNode;
return head;
} else {
move = move->next;
}
}
move->next = newNode;
return head;
}
int main() {
Node* head = getList();
displayList(head);
sortList(head);
displayList(head);
while(1) {
int data;
scanf("%d", &data);
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
head = inserList(head, temp);
displayList(head);
}
return 0;
}