题目描述:输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;
void CreateList(LinkList &L, int n)
{
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
LinkList p, q;
q = L;
for(int i = 0;i< n; i ++)
{
p = (LinkList)malloc(sizeof(LNode));
scanf("%d", &p->data);
if(p->data == -1) break;
p->next = NULL;
q->next = p;
q = p;
}
}
void Split(LinkList &LA, LinkList &LB, LinkList &LC)
{
int b, c;
b = c = 0;
LB = (LinkList)malloc(sizeof(LNode));
LC = (LinkList)malloc(sizeof(LNode));
LB->next = LC->next = NULL;
LinkList p, q, r;
p = LA->next;
q = LB;
r = LC;
while(p)
{
if(p->data % 2 == 0)
{
q->next = p;
q = q->next;
p = p->next;
b++;
}
else
{
r->next = p;
r = r->next;
p = p->next;
c++;
}
}
printf("%d %d\n", b, c);
q = LB->next;
while(b--)
{
if(b != 0)
printf("%d ", q->data);
else
printf("%d\n", q->data);
q = q->next;
}
r = LC->next;
while(c--)
{
if(c != 0)
printf("%d ", r->data);
else
printf("%d\n", r->data);
r = r->next;
}
}
int main()
{
int n;
LinkList LA, LB, LC;
scanf("%d", &n);
CreateList(LA, n);
Split(LA, LB, LC);
return 0;
}