数据结构实验之链表五:单链表的拆分
Time Limit: 1000MS
Memory Limit: 65536KB
Submit
Statistic
Problem Description
输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。
Input
第一行输入整数N;;
第二行依次输入N个整数。
第二行依次输入N个整数。
Output
第一行分别输出偶数链表与奇数链表的元素个数;
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。
Example Input
10 1 3 22 8 15 999 9 44 6 1001
Example Output
4 6 22 8 44 6 1 3 15 999 9 1001
01 | #include <stdio.h> |
02 | #include <stdlib.h> |
03 | struct node |
04 | { |
05 | int data; |
06 | struct node *next; |
07 | }; |
08 | struct nd |
09 | { |
10 | int data1; |
11 | struct nd *next1; |
12 | }; |
13 | int main() |
14 | { |
15 | int n, i, b, count, count1; |
16 | struct node *p, *q, *head; |
17 | struct nd *p1, *q1, *head1; |
18 | head = ( struct node *) malloc ( sizeof ( struct node)); |
19 | head1 = ( struct nd *) malloc ( sizeof ( struct nd)); |
20 | head->next = NULL;head1->next1 = NULL; |
21 | scanf ( "%d" , &n); |
22 | p = head;p1 = head1;count = 0;count1 = 0; |
23 | for (i = 0;i<n;i++) |
24 | { |
25 | q = ( struct node *) malloc ( sizeof ( struct node)); |
26 | q1 = ( struct nd *) malloc ( sizeof ( struct nd)); |
27 | scanf ( "%d" , &b); |
28 | if (b%2==0) |
29 | { |
30 | q->data = b; |
31 | q->next = p->next; |
32 | p->next = q; |
33 | p = q; |
34 | count++; |
35 | } |
36 | else |
37 | { |
38 | q1->data1 = b; |
39 | q1->next1 = p1->next1; |
40 | p1->next1 = q1; |
41 | p1 = q1; |
42 | count1++; |
43 | } |
44 | } |
45 | printf ( "%d %d\n" , count, count1); |
46 | p = head->next; |
47 | while (p->next!=NULL) |
48 | { |
49 | printf ( "%d " , p->data); |
50 | p = p->next; |
51 | } |
52 | printf ( "%d\n" , p->data);p1 = head1->next1; |
53 | while (p1->next1!=NULL) |
54 | { |
55 | printf ( "%d " , p1->data1); |
56 | p1 = p1->next1; |
57 | } |
58 | printf ( "%d\n" , p1->data1); |
59 | return 0; |
60 | } |