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
Hint
不得使用数组!
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define ERROR -1
#define OVERFLOW -2
#define OK 1
typedef int Elemtype;
typedef int Statu;
typedef struct Lnode
{
Elemtype data;
struct Lnode *next;
} Link;
Link * Creat(int n);
Link * Negative(Link *head);
Statu Dis_Link(Link *head);
Statu Split(Link *head);
int main()
{
int n;
Link *head;
scanf("%d", &n);
head = Creat(n);
Split(head);
return 0;
}
Link *Creat(int n)
{
Link *head, *p, *q;
head = (Link *)malloc(sizeof(Link));
head -> next = NULL;
q = head;
while(n--)
{
p = (Link *)malloc(sizeof(Link));
p -> next = NULL;
scanf("%d", &p -> data);
q -> next = p;
q = p;
}
return head;
}
Link * Negative(Link *head)
{
Link *q, *p;
p = head -> next;
head -> next = NULL;
q = p -> next;
while(p)
{
p -> next = head -> next;
head -> next = p;
p = q;
if(q)
{
q = q -> next;
}
}
return head;
}
Statu Dis_Link(Link *head)
{
Link *p;
p = head -> next;
while(p -> next)
{
printf("%d ", p -> data);
p = p -> next;
}
printf("%d\n", p -> data);
return OK;
}
Statu Split(Link *head)
{
Link *p, *q, *r, *head1, *head2, *t;
int k = 0,j = 0;
head1 = (Link *)malloc(sizeof(Link));
head1 -> next = NULL;
head2 = (Link *)malloc(sizeof(Link));
head2 -> next = NULL;
p = head1;
q = head2;
r = head -> next;
while(r)
{
t = (Lnode *)malloc(sizeof(Lnode));
t -> next = NULL;
t -> data = r -> data;
if(t -> data % 2 == 0)
{
q -> next = t;
q = t;
k++;
}
else
{
p -> next = t;
p = t;
j++;
}
r = r -> next;
}
printf("%d %d\n", k, j);
Dis_Link(head2);
Dis_Link(head1);
return OK;
}