sdutacm-数据结构实验之链表六:有序链表的建立
数据结构实验之链表六:有序链表的建立
TimeLimit: 1000MS Memory Limit: 65536KB
SubmitStatistic
输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。
Input
第一行输入整数个数N; 第二行输入N个无序的整数。
Output
依次输出有序链表的结点值。
ExampleInput
6
33 6 22 9 44 5
ExampleOutput
5 6 9 22 33 44
Hint
不得使用数组!
Author
F #include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #include<iostream> #include<algorithm> #include<stack> #include<queue> //#include<dqeue> using namespace std; struct node { int data; struct node*next; }; struct node*creat(struct node*head,int n) { head= (struct node*)malloc(sizeof(struct node)); head->next =NULL; struct node*tail = head; for(int i=1;i<=n;i++) { struct node*p = (struct node*)malloc(sizeof(struct node)); p->next =NULL; scanf("%d",&p->data); tail->next = p; tail = p; } return head; } /*struct node*guibing(struct node*head1,struct node*head2) { head1= head1->next; head2 =head2->next; struct node*tail,*p,*mail; tail = (struct node*)malloc(sizeof(struct node)); mail = tail; while(head1&&head2) { if(head1->data<head2->data) { mail->next = head1; mail = head1; p = head1; head1 = head1->next; p->next =NULL; } else { mail->next =head2; mail = head2; p = head2; head2 = head2->next; p->next =NULL; } } if(head1) { while(head1) { mail->next =head1; mail = head1; p = head1; head1 = head1->next; p->next = NULL; } } else if(head2) { while(head2) { mail->next =head2; mail = head2; p = head2; head2 = head2->next; p->next =NULL; } } return tail; }*/ struct node*search(struct node*head1,int n) { while(n--) { struct node*tail = head1; int key; cin>>key; while(tail->next) { if(tail->next->data>key) { struct node*p; p = (struct node*)malloc(sizeof(struct node)); p->next = NULL; p->data = key; p->next = tail->next; tail->next = p; tail = head1; break; } else tail = tail->next; } if(tail->next==NULL) { struct node*p = (struct node*)malloc(sizeof(struct node)); p->next = NULL; p->data = key; tail->next = p; } } return head1; } void show(struct node*head) { struct node*tail; tail =head; int top = 1; while(tail->next) { if(top)top=0; else printf(" "); printf("%d",tail->next->data); tail = tail->next; } } int main() { int n,n1=0,n2=0; scanf("%d",&n); struct node*head1= (struct node*)malloc(sizeof(struct node)); head1->next =NULL; head1 = search(head1,n); show(head1); cout<<endl; return 0; } /*************************************************** User name: jk160505徐红博 Result: Accepted Take time: 0ms Take Memory: 164KB Submit time: 2017-01-14 17:07:53 ****************************************************/