文章标题

来源:互联网 发布:家境一般出国留学知乎 编辑:程序博客网 时间:2024/06/07 09:30

输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。
输入
第一行输入整数N;;
第二行依次输入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<bits/stdc++.h>
using namespace std;
int count1=0,count2=0;
struct node
{
int data;
struct node *next;
};
struct node *split(struct node *&head)//拆分过程
{
struct node *head1,*tail1,*tail,*p;
head1=new struct node();
head1->next=NULL;//在这就有新建了一个链表
tail1=head1;
tail=head;
p=head->next;
head->next=NULL;
while(p)
{
if(p->data%2==0)
{
tail->next=p;
tail=p;
tail1->next=NULL;//这很重要,因为如果拆分的链表的最后一个元素不是原链表的最后一个元素,那么另一个链表的的最后一个节点的next之不为空,就会有输出错误,这样写就是在偶数时把存奇数链表的最后一个元素的next之附空。
p=p->next;
count1++;
}
else
{
tail1->next=p;
tail1=p;
tail->next=NULL;
p=p->next;
count2++;
}
}
return head1;
};
int main()
{
int x,n,i;
cin>>n;
struct node *head,*tail,*p,*q,*head1;
head=new struct node();
head->next=NULL;
tail=head;
p=new struct node();
for(i=1;i<=n;i++)
{
cin>>x;
p->data=x;
p->next=NULL;
tail->next=p;
tail=p;
p=new struct node();
}
head1=split(head);
cout<<count1<<" "<<count2<<endl;
for(p=head->next;p!=NULL;p=p->next)
{
cout<<p->data<<" ";
}
cout<<endl;
for(p=head1->next;p!=NULL;p=p->next)
{
cout<<p->data<<" ";
}
return 0;
}

0 0