输入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>
struct node
{
int data;
struct node*next;
};
struct node*creat(int n)
{
struct node*head,*p,*tail;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
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;
}
return head;
}
int main()
{
//输入
int n;
scanf("%d",&n);
//顺序建立链表并输入
struct node*head;
head=creat(n);
//链表的拆分
int x=0;
int y=0;//用来计数
//再建立一个链表用来放拆分之后的奇数,偶数直接用原链表存放
struct node *head1;
head1=(struct node*)malloc(sizeof(struct node));
head1->next=NULL;
//把原链表的头结点释放出来,用来存放偶数,释放头结点需要抓住后面的结点,防止后续结点游离
//所以需要工作指针p指向链表的第一个实际结点,q指向第二个实际结点
//另外因为后面要把拆分出的结点顺序插入到新链表中,所以还要两个工作指针tail1,tail2
struct node*p,*q,*tail1,*tail2;
p=head->next;
q=p->next;
head->next=NULL;//释放head
tail1=head;
tail2=head1;
//接下来开始按要求拆分了
//开始遍历
while(p)
{
if(p->data%2==0)//如果是偶数,就插在head后面
{
p->next=NULL;
tail1->next=p;
tail1=p;
p=q;
q=q->next;
x++;
}
else//如果是奇数就插在head1的后面
{
p->next=NULL;
tail2->next=p;
tail2=p;
p=q;
q=q->next;
y++;
}
}
//拆分完成之后开始输出
printf("%d %d\n",x,y);
struct node*j,*k;
j=head->next;//将两个拆分之后的游动指针进行初始化的定位
k=head1->next;
while(j)//分别输出两个链表
{
if(j->next==NULL)
printf("%d\n",j->data);
else
printf("%d ",j->data);
j=j->next;
}
while(k)
{
if(k->next==NULL)
printf("%d\n",k->data);
else
printf("%d ",k->data);
k=k->next;
}
return 0;
}