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

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

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 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;
}


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