欢迎提问,随时作答!
Description
输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。
Input
第一行输入整数N;;
第二行依次输入N个整数。
Output
第一行分别输出偶数链表与奇数链表的元素个数;
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。
Sample
Input
10
1 3 22 8 15 999 9 44 6 1001
Output
4 6
22 8 44 6
1 3 15 999 9 1001
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <math.h>
using namespace std;
//定义结构体
typedef struct node
{
int data;
struct node *next;
} Node;
//创建链表
Node *creat(int n)
{
Node *tail,*p,*head;
head=(Node *)malloc(sizeof(Node));
head->next=NULL;
tail=head;
for(int i=1; i<=n; i++)
{
p=(Node *)malloc(sizeof(Node));
scanf("%d",&p->data);
tail->next=p;
tail=p;
p->next=NULL;
}
return head;
}
//输出链表
void ouput(Node *head)
{
Node *p;
p=head->next;
while(p->next!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("%d\n",p->data);
}
//链表拆分
Node *spilt(Node *head1)
{
int cnt1=0,cnt2=0;//定义计数变量
Node *p,*head2,*tail1,*tail2;
head2=(Node *)malloc(sizeof(Node));//新开一个头节点
head2->next=NULL;
tail2=head2;
p=head1->next;
tail1=head1;//为拆分做准备
head1->next=NULL;
while(p)
{
if(p->data%2==0)//偶数时
{
tail1->next=p;//改变指向后,tail更新
tail1=p;
cnt1++;
}
else
{
tail2->next=p;
tail2=p;
cnt2++;
}
p=p->next;//继续处理下一个
}
tail1->next=NULL;//结尾保证置空,不乱指
tail2->next=NULL;
printf("%d %d\n",cnt1,cnt2);
return head2;
}
int main()
{
int n;
Node *head1,*head2;
cin>>n;
head1=creat(n);
head2=spilt(head1);
ouput(head1);
ouput(head2);
return 0;
}