Problem Description
Input
第二行依次输入N个整数。
Output
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。
Example Input
10 1 3 22 8 15 999 9 44 6 1001
Example Output
4 6 22 8 44 61 3 15 999 9 1001
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; struct node *creatData(int n) //逆序建表,链表的初始化 { struct node *head,*p,*q; int i; head=(struct node*)malloc(sizeof(struct node)); head->next=NULL; q=head; for(i=0;i<n;i++) { p=(struct node*)malloc(sizeof(struct node)); scanf("%d",&p->data); p->next=NULL; q->next=p; q=p; } return head; }; struct node *split(struct node *head1)//链表的拆分 { struct node *head2,*p,*q; int s1=0,s2=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; s1++; } else { p->next=head2->next; head2->next=p; s2++; } p=q; if(q!=NULL) q=q->next; } printf("%d %d\n",s1,s2); return head2; }; void printfData(struct node *head)//遍历链表 { struct node *p; p=head->next; while(p!=NULL) { if(p->next==NULL) printf("%d\n",p->data); else printf("%d ",p->data); p=p->next; } } int main() { int n; struct node *head1,*head2; scanf("%d",&n); head1=creatData(n); head2=split(head1); printfData(head1); printfData(head2); return 0; }