資料結構實驗之鏈表五:單鏈表的拆分,資料結構單鏈
資料結構實驗之鏈表五:單鏈表的拆分 Time Limit: 1000MS Memory limit: 65536K 題目描述輸入N個整數順序建立一個單鏈表,將該單鏈表拆分成兩個子鏈表,第一個子鏈表存放了所有的偶數,第二個子鏈表存放了所有的奇數。兩個子鏈表中資料的相對次序與原鏈表一致。輸入第一行輸入整數N;;
第二行依次輸入N個整數。輸出第一行分別輸出偶數鏈表與奇數鏈表的元素個數;
第二行依次輸出偶數子鏈表的所有資料;
第三行依次輸出奇數子鏈表的所有資料。樣本輸入
101 3 22 8 15 999 9 44 6 1001
樣本輸出
4 622 8 44 6 1 3 15 999 9 1001
提示不得使用數組!來源
#include<stdio.h>#include<stdlib.h>struct node { int data; struct node *next;};struct node *Creat(int n){ struct node *head, *tail, *p; int i; head=(struct node *)malloc(sizeof(struct node)); head->next=NULL; for(i=1;i<=n;i++) { p=(struct node *)malloc(sizeof(struct node)); scanf("%d",&p->data); p->next=head->next; head->next=p; } return head;}struct node * Split(struct node * head1){ struct node *head2, *p, *q; int a=0, b=0; head2=(struct node *)malloc(sizeof(struct node)); head2->next=NULL; p=head1->next; head1->next=NULL; q=p->next; while(p!=NULL) { if(p->data%2==0) { p->next=head1->next; head1->next=p; a++; } else { p->next=head2->next; head2->next=p; b++; } p=q; if(q!=NULL) q=q->next; } printf("%d %d\n",a,b); return head2;};int main(){ int n; struct node * head1, *head, *p, *q; scanf("%d",&n); head=Creat(n); head1=Split(head); p=head->next; while(p!=NULL) { if(p->next!=NULL) printf("%d ",p->data); else printf("%d\n",p->data); p=p->next; } q=head1->next; while(q!=NULL) { if(q->next!=NULL) printf("%d ",q->data); else printf("%d\n",q->data); q=q->next; } return 0;}