数据结构实验之链表五:单链表的拆分
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 <stdio.h>
#include <stdlib.h>
struct LNode
{
int data;
struct LNode *next;
};
void creat(struct LNode *head,int n);
int getsize(struct LNode *head);
void print(struct LNode *head);
int main()
{
// freopen("my.in","r",stdin);
struct LNode h1,h2,h3;//h2偶数,h3奇数
struct LNode *tail1,*tail2,*tail3;
struct LNode *p;
int n;
scanf("%d",&n);
creat(&h1,n);
tail1 = h1.next;
tail2 = &h2;
tail3 = &h3;
while(tail1)//知道h1处理完
{
if(tail1->data % 2 == 0)//如果为偶数
{
p = (struct LNode *)malloc(sizeof(struct LNode));
p->next = NULL;
p->data = tail1->data;
tail2->next = p;
tail2 = p;
} //
else//如果为奇数
{
p = (struct LNode *)malloc(sizeof(struct LNode));
p->next = NULL;
p->data = tail1->data;
tail3->next = p;
tail3 = p;
}
tail1 = tail1->next;
}
printf("%d %d\n",getsize(&h2),getsize(&h3));
print(&h2);
print(&h3);
return 0;
}
void creat(struct LNode *head,int n)
{
struct LNode *tail,*p;
int i;
tail = head;
tail->next = NULL;
for(i=0; i<n; i++)
{
p = (struct LNode *)malloc(sizeof(struct LNode));
p->next = NULL;
scanf("%d", &p->data);
tail->next = p;
tail = p;
}
}
void print(struct LNode *head)
{
struct LNode *p;
p = head->next;
while(p->next)
{
printf("%d ",p->data);
p = p->next;
}
printf("%d\n",p->data);
}
int getsize(struct LNode *head)
{
struct LNode *p;
int n=0;
p = head->next;
while(p)
{
n++;
p = p->next;
}
return n;
}