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

G - 数据结构实验之链表五:单链表的拆分
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
不得使用数组!

#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct node
{
int data;
struct node *next;
}*h,*p,*h1,h2,t,t1,t2;
int main()
{
int n;
int i;
int o=0,j=0;
scanf("%d",&n);
h=(struct node
)malloc(sizeof(struct node));
h->next=NULL;
t=h;
for(i=0; i<n; i++)
{
p=(struct node
)malloc(sizeof(struct node));
p->next=NULL;
scanf("%d",&p->data);
if(p->data%2==0)o++;
else j++;
t->next=p;
t=p;
}
h1=(struct node
)malloc(sizeof(struct node));
h2=(struct node
)malloc(sizeof(struct node));
h1->next=NULL;
h2->next=NULL;
t1=h1;
t2=h2;
p=h->next;
for(i=0; i<n; i++)
{
if(p->data%2==0)
{
t1->next=p;
t1=p;
p=p->next; //这一步一定要在这里,让p走到下一个节点,因为在下一局就要让h这条链的
t1->next=NULL; //这一个节点指向NULL了
}
else
{
t2->next=p;
t2=p;
p=p->next;
t2->next=NULL;
}
}
printf("%d %d\n",o,j);
p=h1->next;
printf("%d",p->data);
while(p->next!=NULL)
{
p=p->next;
printf(" %d",p->data);
}
printf("\n");
p=h2->next;
printf("%d",p->data);
while(p->next!=NULL)
{
p=p->next;
printf(" %d",p->data);
}
printf("\n");
return 0;
}

发布了37 篇原创文章 · 获赞 3 · 访问量 717

猜你喜欢

转载自blog.csdn.net/Are_you_ready/article/details/104763552
今日推荐