数据结构实验之链表五:单链表的拆分
Description
输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。
Input
第一行输入整数N;;
第二行依次输入N个整数。
Output
第一行分别输出偶数链表与奇数链表的元素个数;
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。
Sample
Input
10 1 3 22 8 15 999 9 44 6 1001
Output
4 6 22 8 44 6 1 3 15 999 9 1001
Hint
不得使用数组!
SubmitSolutionsTopics
代码:
#include<bits/stdc++.h>
using namespace std;
typedef struct Lnode
{
int data;
struct Lnode *next;
}Lnode ,*Linklist;
int sum1 = 0, sum2 = 0;
void createlist(struct Lnode *l,int n)
{
struct Lnode *h = l;
for(int i = 0; i < n; i++)
{
int a;
cin >> a;
struct Lnode *p = new Lnode;
p -> data = a;
p -> next = NULL;
h -> next = p;
h = p;
}
}
void split(Linklist l,Linklist l1,Linklist l2)
{
Linklist p = l -> next;
Linklist p1 = l1 ;
Linklist p2 = l2 ;
while(p)
{
if((p->data%2) == 0)
{
p1 -> next = p;
p1 = p;
p = p->next;
sum1++;
}
else
{
p2 -> next = p;
p2 = p;
p = p ->next;
sum2++;
}
}
p1 -> next = NULL;
p2 -> next = NULL;
}
int main()
{
int n;
cin >> n;
struct Lnode *l = new Lnode;
struct Lnode *l1 = new Lnode;
struct Lnode *l2 = new Lnode;
l -> next = NULL;
l1 -> next = NULL;
l2 -> next = NULL;
createlist(l,n);
split(l,l1,l2);
cout << sum1 << " " << sum2 << endl;
while(l1->next)
{
cout << l1->next->data;
l1 = l1 -> next;
if(l1->next == NULL)
cout << endl;
else
{
cout << " ";
}
}
while(l2->next)
{
cout << l2->next->data;
l2 = l2 -> next;
if(l2->next == NULL)
cout << endl;
else
{
cout << " ";
}
}
return 0;
}