数据结构——链表之单链表的拆分
2017-10-06 18:22
197 查看
数据结构实验之链表五:单链表的拆分
Time Limit: 1000MS Memory Limit: 65536KB[align=center]Submit Statistic[/align]
Problem Description
输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。Input
第一行输入整数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
Hint
01 | #include <stdio.h> |
02 | #include <stdlib.h> |
03 | int x,y; |
04 | struct node |
05 | { |
06 | int data; |
07 | struct node *next; |
08 | }; |
09 | struct node *build( struct node *head, int n) //逆序建立链表 |
10 | { |
11 | int i; |
12 | struct node *p; |
13 | head->next=NULL; |
14 | for (i=1; i<=n; i++) |
15 | { |
16 | p=( struct node*) malloc ( sizeof ( struct node)); |
17 | scanf ( "%d" ,&p->data); |
18 | p->next=head->next; |
19 | head->next=p; |
20 | } |
21 | return (head); |
22 | } |
23 | struct node *show( struct node *head) |
24 | { |
25 | struct node *p; |
26 | p=( struct node*) malloc ( sizeof ( struct node)); |
27 | p=head->next; |
28 | while (p) |
29 | { |
30 | if (p->next!=NULL) |
31 | { |
32 | printf ( "%d " ,p->data); |
33 | } |
34 | else |
35 | { |
36 | printf ( "%d\n" ,p->data); |
37 | } |
38 | p=p->next; |
39 | } |
40 | return (head); |
41 | } |
42 | struct node *fen( struct node *head1) //逆序拆分 |
43 | { |
44 | x=y=0; |
45 | struct node *p,*q,*head2; |
46 | head2=( struct node*) malloc ( sizeof ( struct node)); |
47 | head2->next=NULL; |
48 | p=head1->next; |
49 | head1->next=NULL; |
50 | q=p->next; |
51 | while (p) |
52 | { |
53 | if (p->data%2==0) |
54 | { |
55 | x++; |
56 | p->next=head1->next; |
57 | head1->next=p; |
58 | } |
59 | else |
60 | { |
61 | y++; |
62 | p->next=head2->next; |
63 | head2->next=p; |
64 | } |
65 | p=q; |
66 | if (q) |
67 | q=q->next; |
68 | } |
69 | printf ( "%d %d\n" ,x,y); |
70 | show(head1); |
71 | show(head2); |
72 | return (head1); |
73 | } |
74 | int main() |
75 | { |
76 | int n; |
77 | struct node *head1; |
78 | head1=( struct node*) malloc ( sizeof ( struct node)); |
79 | scanf ( "%d" ,&n); |
80 | build(head1,n); |
81 | fen(head1); |
82 | return 0; |
83 | } |
84 |
85 |
86 | /*************************************************** |
87 | User name: jk160618郭衣鹏 |
88 | Result: Accepted |
89 | Take time: 0ms |
90 | Take Memory: 152KB |
91 | Submit time: 2017-10-07 09:16:28 |
92 | ****************************************************/ |
相关文章推荐
- SDUT OJ 数据结构实验之链表五:单链表的拆分
- SDUT 2120 数据结构实验之链表五:单链表的拆分
- SDUT-数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- SDUT 2120 数据结构实验之链表五-单链表的拆分
- sdutacm- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 2120 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- SDUTACM 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- SDUT 2120 数据结构实验之链表五:单链表的拆分
- 【2120】数据结构实验之链表五:单链表的拆分
- 2120-数据结构实验之链表五:单链表的拆分
- SDUT 2120 数据结构实验之链表五:单链表的拆分 解法2