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

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

2019-07-27 21:20 239 查看

数据结构实验之链表五:单链表的拆分
Time Limit: 1000 ms Memory Limit: 65536 KiB
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<bits/stdc++.h>

using namespace std;

struct node
{
node *next;
int data;
};
void creat(node *l, int n)
{
node *p, *t;
t = l;
int x;
for(int i = 0; i < n; i++)
{
cin>>x;
p = (node *)malloc(sizeof(node));
p->data = x;
t->next = p;
p->next = NULL;
t = p;
}
}
void display(node *l, node *l1, node *l2)
{
node *p, *q, *t;
p = l1;
q = l2;
t = l->next;
while(t)
{
if(t->data % 2 == 0)
{
p->next = t;
p = t;///延续下去,好继续接下来的插入
}
else
{
q->next = t;
q = t;///
}
t = t->next;///继续下一个数
}
p->next = NULL;///链表的最后为空,利于输出判断
q->next = NULL;
}
int length(node *l)
{
node *p;
p = l->next;
int s = 0;
while§
{
s++;
p = p->next;
}
return s;
}
void print(node *l)
{
node *p;
p = l->next;
while§
{
if(p->next == NULL)
{
cout<data<<endl;
}
else
cout<data<<" “;
p = p->next;
}
}
int main()
{
node *l, *l1, *l2;
int n;
cin>>n;
l = (node *)malloc(sizeof(node ));
l1 = (node *)malloc(sizeof(node));
l2 = (node *)malloc(sizeof(node));
creat(l, n);
display(l, l1, l2);
cout<<length(l1)<<” "<<length(l2)<<endl;
print(l1);
print(l2);
return 0;
}

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