1. 程式人生 > >2119=數據結構實驗之鏈表四:有序鏈表的歸並

2119=數據結構實驗之鏈表四:有序鏈表的歸並

nbsp scanf eof ret div spa 數據 sizeof else

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 struct node
 4 {
 5     int data;
 6     struct node*next;
 7 };
 8 int main()
 9 {
10     int i,n,m;
11     struct node*head,*head1,*end1,*end,*p,*q;
12     head=(struct node*)malloc(sizeof(struct node));
13     head1=(struct node*)malloc(sizeof
(struct node));//這裏我用了兩個鏈表的頭尾,一個中轉站P。 14 head->next=NULL; 15 head1->next=NULL; 16 end=head; 17 end1=head1; 18 scanf("%d %d",&n,&m); 19 for(i=0; i<n; i++) 20 { 21 p=(struct node*)malloc(sizeof(struct node)); 22 scanf("%d",&p->data);
23 p->next=NULL; 24 end->next=p; 25 end=p; 26 } 27 for(i=0; i<m; i++) 28 { 29 p=(struct node*)malloc(sizeof(struct node)); 30 scanf("%d",&p->data); 31 p->next=NULL; 32 end1->next=p; 33 end1=p;
34 } 35 q=head->next; 36 head->next=NULL; 37 end=head; 38 p=head1->next; 39 while(p&&q) 40 { 41 if(p->data<q->data) 42 { 43 end->next=p; 44 end=p; 45 p=p->next; 46 } 47 else 48 { 49 end->next=q; 50 end=q; 51 q=q->next; 52 } 53 if(p) 54 end->next=p; 55 else 56 end->next=q;//這裏是為了最後一個,以免漏一個,跟大神學的=。=。 57 } 58 for(p=head->next; p; p=p->next) 59 { 60 61 printf("%d",p->data); 62 if(p->next!=NULL)printf(" "); 63 } 64 65 return 0; 66 }

2119=數據結構實驗之鏈表四:有序鏈表的歸並