數據結構實驗之鏈表五:單鏈表的拆分

數據結構實驗之鏈表五:單鏈表的拆分

Time Limit: 1000ms   Memory limit: 65536K  有疑問?點這裏^_^

題目描述

輸入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 node
{
	int data;
	struct node *next;
};
int main()
{
	int m,s=0,i;
	struct node *head,*p,*tail,*head1,*tail1;
	head=(struct node*)malloc(sizeof(struct node));
	head1=(struct node*)malloc(sizeof(struct node));
	head->next=NULL;
	tail=head;
	head1->next=NULL;
	tail1=head1;
	scanf("%d",&m);
	for(i=0;i<m;i++)
	{
		p=(struct node*)malloc(sizeof(struct node));
		scanf("%d",&p->data);
		if(p->data%2==0)
		{
			p->next=NULL;
			tail->next=p;
			tail=p;
			s++;
		}
		else 
		{
			p->next=NULL;
			tail1->next=p;
			tail1=p;
		}
	}
	printf("%d %d\n",s,m-s);
	for(p=head->next;p;p=p->next)
	{
		if(p->next)printf("%d ",p->data);
		else printf("%d\n",p->data);
	}
	for(p=head1->next;p;p=p->next)
	{
		if(p->next)printf("%d ",p->data);
		else printf("%d\n",p->data);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章