数据结构实验之链表五:单链表的拆分
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
Problem Description
输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。
Input
第一行输入整数N;;
第二行依次输入N个整数。
Output
第一行分别输出偶数链表与奇数链表的元素个数;
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。
Sample Input
10
1 3 22 8 15 999 9 44 6 1001
Sample Output
4 6
22 8 44 6
1 3 15 999 9 1001
#include <iostream>
#include<bits/stdc++.h>
struct st *h1,*h2,*t1,*t2;
int a=0,b=0;
using namespace std;
struct st
{
int data;
struct st *next;
};
struct st *cr(int n)
{
struct st *head,*t,*p;
int i;
head=(struct st*)malloc(sizeof(struct st));
head->next=NULL;
t=head;//不要忘记
for(i=0;i<n;i++)
{
p=(struct st*)malloc(sizeof(struct st));
scanf("%d",&p->data);
p->next=NULL;
t->next=p;
t=p;}
return head;
}
void sq(struct st *h)
{
struct st *p;
p=h->next;
h1=(struct st*)malloc(sizeof(struct st));
h2=(struct st*)malloc(sizeof(struct st));
h1->next=NULL;t1=h1;
h2->next=NULL;
t2=h2;
while(p)
{
if(p->data%2==0)
{t1->next=p;
t1=p;a++;}
else {t2->next=p;
t2=p;b++;}
p=p->next;
}
t1->next=NULL;
t2->next=NULL;
}
void pr(struct st *h)
{
struct st*p;
int n=0;
p=h->next;
while(p)
{n++;
if(n==1)
printf("%d",p->data);
else printf(" %d",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
int n;
struct st*h;
scanf("%d",&n);
h=cr(n);
sq(h);
printf("%d %d\n",a,b);
pr(h1);
pr(h2);
return 0;
}