数据结构实验之链表五:单链表的拆分
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
不得使用数组!
代码如下:使用原来链表保存偶数和新建链表保存奇数试了一下,效果还不错;
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
struct node *next;
} *head1, *head2, *tail, *p, *q;
int main(){
int N;
while(~scanf("%d", &N)){
int a = N;
head1 = (struct node *)malloc(sizeof(struct node));
head1->next = NULL;
tail = head1;
for(int i = 0; i < N; i++){
p = (struct node *)malloc(sizeof(struct node));
p->next = NULL;
scanf("%d", &p->data);
tail->next = p;
tail = p;
}
p = head1->next;
tail = head1; //直接用原来的链表保存偶数
head2 = (struct node *)malloc(sizeof(struct node));
head2->next = NULL;
q = head2;
while(p){
if(p->data % 2){
tail->next = p->next; //直接跳过奇数
q->next = p; // 把奇数存在head2链表
q = p; //指针后移
a--; //总数减去奇数个数
}
else tail = p; // 如果是偶数则指针后移
p = p->next;
}
printf("%d %d\n", a, N - a);
p = head1->next;
while(p){
printf("%d%c", p->data, p->next?' ':'\n');
p = p->next;
}
p = head2->next;
while(p){
printf("%d%c", p->data, p->next?' ':'\n');
p = p->next;
}
}
return 0;
}
第一次使用这样的代码风格,有点不适应。。。