输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。
输入格式:
第一行输入整数N(1<=N<=100000)。
第二行依次输入N个整数。 (保证奇数偶数都存在)
输出格式:
第一行分别输出偶数链表与奇数链表的元素个数;
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。
输入样例:
10
1 3 22 8 15 999 9 44 6 1001
输出样例:
4 6
22 8 44 6
1 3 15 999 9 1001
#include <stdio.h>
#include <stdlib.h>
typedef struct node { // 使用typedef后,再次定义该类型结构体可以忽略struct的书写
int data;
struct node *next;
}node;
int ji, ou;
node *creat(int n) { // 建表
node *head, *p;
head = (node*)malloc(sizeof(node));
head->next = NULL;
for ( int i = 0; i < n; i++) {
p = (node*)malloc(sizeof(node));
scanf("%d", &p->data);
p->next = head->next;
head->next = p;
}
return head;
}
node *split(node *head1) { // 拆分
node *head2, *p, *q;
head2 = (node*)malloc(sizeof(node));
head2->next = NULL;
p = head1->next;
q = p->next;
head1->next = NULL;
while(p) {
if ( p->data%2 == 0 ) {
ou++;
p->next = head1->next;
head1->next = p;
}
else {
ji++;
p->next = head2->next;
head2->next = p;
}
p = q;
if (q)
q = q->next;
}
return head2;
}
void pri(node *p) { // 输出
while(p) {
if ( p->next == NULL )
printf("%d\n", p->data);
else
printf("%d ", p->data);
p = p->next;
}
}
int main() {
int n;
scanf("%d", &n);
node *head1, *head2;
head1 = creat(n);
head2 = split(head1);
printf("%d %d\n", ou, ji);
pri(head1->next);
pri(head2->next);
return 0;
}