#include <stdio.h>
#include <stdlib.h>
typedef struct link {
int value;
struct link *next;
} link;
link *create_link(int value) {
link *node = (link *) malloc(sizeof(link));
if (node == NULL) {
exit(-1);
}
node->next = NULL;
node->value = value;
return node;
}
- 两种插入:
1.头插法,不论结点大小
2.有序插入
link *insert(link *node,int value){
link *p = create_link(value);
p->next = node->next;
node->next = p;
return node;
}
link *insert_sort(link *node,int value){
link *p = node;
if(p->next==NULL){
p->next = create_link(value);
return node;
}
while (p->next!=NULL){
if(value>=p->next->value){
p = p->next;
}else{
link *temp = create_link(value);
temp->next = p->next;
p->next = temp;
return node;
}
}
p->next = create_link(value);
return node;
}
void display(link *node){
while (node->next!=NULL){
printf("%d ",node->next->value);
node = node->next;
}
printf("\n");
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
int i,num;
link *node = create_link(-1);
link *node_sort = create_link(-1);
for(i=0;i<n;i++){
scanf("%d",&num);
insert(node,num);
insert_sort(node_sort,num);
}
printf("no sort(head_insert):");
display(node);
printf("sort:");
display(node_sort);
}
}
输入样例1:
5
3 2 1 4 5
输入样例2:
12
23 34 2 21 45 7 8 0 90 99 15 100
可多组输入,符合牛客OJ输入样式
5
3 2 1 4 5
no sort(head_insert):5 4 1 2 3
sort:1 2 3 4 5
12
23 34 2 21 45 7 8 0 90 99 15 100
no sort(head_insert):100 15 99 90 0 8 7 45 21 2 34 23
sort:0 2 7 8 15 21 23 34 45 90 99 100