c/c++:单链表的拆分

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <cstring>
using namespace std;
struct node
{
int data;
struct node *next;
};

int main ()
{
std::ios::sync_with_stdio(false);

struct node *head , *tail,*p;

head =new node;
head->next = NULL;
tail = head;

int num;
int sum1,sum2;

cin>>num;
while(num--)
{
p = new node ;
cin>>p->data;
tail->next = p;
tail = tail->next;
}
p->next = NULL;


struct node *head1 , *head2 ,*tail1,*tail2;

head1 = new node;
head1->next = NULL;
tail1 = head1;

head2 = new node;
head2->next = NULL;
tail2 =head2;

p = head->next;
sum1 = 0;
sum2 = 0;
while(p!=NULL){

if(p->data%2 ==1){
tail1->next = p;
tail1 = tail1->next;
sum1 +=1;
} else {
tail2->next = p;
tail2 = tail2->next;
sum2 +=1;
}
p = p->next;
}
tail1->next = NULL;
tail2->next = NULL;
cout << sum2 << ' '<<sum1<<endl;

p = head2->next;
while(p!=NULL){
cout<<p->data;
if(p->next!=NULL){
cout<< ' ';
}
p = p->next;

}
cout<<endl;

p = head1->next;
while(p!=NULL){
cout<<p->data;
if(p->next!=NULL){
cout<< ' ';
}
p = p->next;

}
cout<<endl;

return 0;

}