您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之链表五:单链表的拆分

2016-01-29 11:19 525 查看

题目描述

输入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

提示

不得使用数组!

来源

示例程序

最近几天一直在练单向链表,从开始的没思路,不会写到现在能做出来,感觉棒棒的。虽然算法可能不是最好的,但毕竟成长了。

按照题意建立一个链表把数据存进去。然后再开两个链表,遍历存数据的链表,把基数和偶数分别提取出来。

AC代码

//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <stack>
#include <set>
#include <queue>
#include <algorithm>
#define CLR(a, b) memset(a, (b), sizeof(a))
#define INF 0x3f3f3f3f
#define eps 1e-8
typedef long long LL;
using namespace std;
typedef struct Node
{
int date;
struct Node *next;
} node;

node *creat(int n)
{
node *head=(node *)malloc(sizeof(node));
head->next=NULL;
node *pr=head;
for(int i=0; i<n; i++)
{
int date;
scanf("%d",&date);
if(i==0)
{
pr->date=date;
}
else
{
node *p=(node *)malloc(sizeof(node));
p->date=date;
p->next=NULL;
pr->next=p;
pr=pr->next;
}
}
return head;
}
void divide(int *j,int *o,node *head,node *headj,node *heado)
{
node *pr=head;
node *prj=headj;
node *pro=heado;
while(pr)
{
if(pr->date%2)
{
if(*j==0)
{
prj->date=pr->date;
prj->next=NULL;
pr=pr->next;
(*j)++;
}
else
{
node *p=(node *)malloc(sizeof(node));
p->date=pr->date;
p->next=NULL;
prj->next=p;
prj=prj->next;
pr=pr->next;
(*j)++;
}
}
else
{
if(*o==0)
{

pro->date=pr->date;
pro->next=NULL;
pr=pr->next;
(*o)++;
}
else
{
node *p=(node *)malloc(sizeof(node));
p->date=pr->date;
p->next=NULL;
pro->next=p;
pro=pro->next;
pr=pr->next;
(*o)++;
}
}

}
}
void show(node *head)
{
node *pr=head;
while(pr->next)
{
printf("%d ",pr->date);
pr=pr->next;
}
printf("%d\n",pr->date);
}
int main()
{
#ifdef LOCAL
freopen("E://in.txt","r",stdin);
#endif // LOCAL
int n;
scanf("%d",&n);
node *head=creat(n);
int j=0,o=0;
node *headj=(node *)malloc(sizeof(node));
node *heado=(node *)malloc(sizeof(node));
divide(&j,&o,head,headj,heado);
printf("%d %d\n",o,j);
show(heado);
show(headj);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 数据结构