数据结构实验之链表五:单链表的拆分

数据结构实验之链表五:单链表的拆分

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。

Input

第一行输入整数N;;
第二行依次输入N个整数。

Output

第一行分别输出偶数链表与奇数链表的元素个数; 
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。

Sample Input

10
1 3 22 8 15 999 9 44 6 1001

Sample Output

4 6
22 8 44 6 
1 3 15 999 9 1001

Hint

不得使用数组!

Source

 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 n,i,a,b,x;
11     a=b=0;
12     struct node *head1,*head2,*p,*q,*tail1,*tail2;
13     scanf("%d",&n);
14     head1=(struct node *)malloc(sizeof(struct node));
15     head2=(struct node *)malloc(sizeof(struct node));
16     head1->next=NULL;
17     head2->next=NULL;
18     tail1=head1;
19     tail2=head2;
20           for(i=0; i<n; i++)
21     {
22         scanf("%d",&x);
23         if(x%2==0)
24         {
25             p=(struct node *)malloc(sizeof(struct node));
26             p->data=x;
27             p->next=NULL;
28             tail1->next=p;
29             tail1=p;
30             a++;
31         }
32         else
33         {
34             q=(struct node *)malloc(sizeof(struct node));
35             q->data=x;
36             q->next=NULL;
37             tail2->next=q;
38             tail2=q;
39             b++;
40         }
41     }
42     printf("%d %d
",a,b);
43     for(p=head1->next; p!=NULL; p=p->next)
44     {
45         if(p->next==NULL)
46         {
47             printf("%d
",p->data);
48         }
49         else printf("%d ",p->data);
50     }
51     for(p=head2->next; p!=NULL; p=p->next)
52     {
53         if(p->next==NULL)
54         {
55             printf("%d
",p->data);
56         }
57         else printf("%d ",p->data);
58     }
59     return 0;
60 }
原文地址:https://www.cnblogs.com/xiaolitongxueyaoshangjin/p/12074738.html