数据结构实验之链表五:单链表的拆分
Time Limit: 1000MS Memory limit: 65536K
题目描述
输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。
输入
第一行输入整数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 <iostream>
#include <string>
#include <cstdio>
#include <string.h>
#include <algorithm>
#include <ctype.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
struct node *creat(int n)
{
int i;
struct node *head, *tail, *p;
head=new node;
head->next=NULL;
tail=head;
for(i=0; i<n; i++)
{
p=new node;
cin>>p->data;
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
}
int main()
{
int n;
int len1, len2;
int i, j;
cin>>n;
struct node *head, *w, *h1, *t1, *h2, *t2;
head = creat(n);
len1=0;
len2=0;
w=head->next;
delete head;
h1=new node; h1->next=NULL; t1=h1;
h2=new node; h2->next=NULL; t2=h2;
for(i=0; i<n; i++)
{
if( w->data%2==0 )
{
t1->next=w;
t1=t1->next;
w=w->next;
len1++;
}
else
{
t2->next=w;
t2=t2->next;
w=w->next;
len2++;
}
}
cout<<len1<<' '<<len2<<endl;
w=h1->next;
delete h1;
for(j=0; j<len1; j++)
{
if(j==0)
cout<<w->data;
else
cout<<" "<<w->data;
w=w->next;
}
cout<<endl;
w=h2->next;
delete h2;
for(j=0; j<len2; j++)
{
if(j==0)
cout<<w->data;
else
cout<<" "<<w->data;
w=w->next;
}
cout<<endl;
return 0;
}