王道数据结构第41页第11题

题目要求:
在这里插入图片描述
代码实现:

#include<stdio.h>
#include<stdlib.h>

#define ElemType int
typedef struct LNode{
	ElemType data;
	struct LNode* next;
}LNode,*LinkList;

LinkList Link_TailInsert(LinkList &L)
{
	int x;
	L=(LinkList)malloc(sizeof(LNode));
	L->next=NULL;
	LNode *r=L,*s;
	scanf("%d",&x);
	while(x!=9999)
	{
		s=(LNode*)malloc(sizeof(LNode));
		s->data=x;
		s->next=r->next;
		r->next=s;
		r=s;
		scanf("%d",&x);
	}
	return L;
}

//将单链表hc拆成A和B两个单链表:
void CutList(LinkList &hc,LinkList &A,LinkList &B)
{
	A=hc; 
	B=(LinkList)malloc(sizeof(LNode));
	LNode *p,*q;
    p=A->next;
	B->next=hc->next->next;q=B->next;
	hc=B->next->next;
	B->next->next=NULL;
	int i=1;
	while(hc)
	{
		if(i%2!=0)
		{
			p->next=hc;
			p=p->next;hc=hc->next;
		}
		else
		{
			q=hc;hc=hc->next;
			q->next=B->next;
			B->next=q;
		}
		i++;
	}
	p->next=NULL;
}

void ShowList(LinkList L)
{
	LNode *p=L->next;
	while(p)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n");
}

void DestroyLinkList(LinkList &L)
{
	LNode* p;
	while(L)
	{
		p=L;
		L=L->next;
		free(p);
	}
	return;
}

int main()
{
	LinkList hc,A,B;
	
	printf("构造数量为偶数个的单链表hc:\n");
	hc=Link_TailInsert(hc);
	
	//将单链表hc拆成A和B两个等长单链表: 
	CutList(hc,A,B);
	
	printf("输出链表A的值:\n");
	ShowList(A);
	printf("输出链表B的值:\n");
	ShowList(B);
	
	DestroyLinkList(A);
	DestroyLinkList(B);
	return 0;
} 

接下来再实现一下王道论坛视频在讲解此题时提供的代码:

#include<stdio.h>
#include<stdlib.h>

#define ElemType int
typedef struct LNode{
	ElemType data;
	struct LNode* next;
}LNode,*LinkList;

LinkList Link_TailInsert(LinkList &L)
{
	int x;
	L=(LinkList)malloc(sizeof(LNode));
	L->next=NULL;
	LNode *r=L,*s;
	scanf("%d",&x);
	while(x!=9999)
	{
		s=(LNode*)malloc(sizeof(LNode));
		s->data=x;
		s->next=r->next;
		r->next=s;
		r=s;
		scanf("%d",&x);
	}
	return L;
}

//将单链表hc拆成A和B两个单链表:
LinkList DisCreate_2(LinkList &A)
{
	LinkList B=(LinkList)malloc(sizeof(LNode));
	B->next=NULL;
	LNode *p=A->next,*q;
	LNode *ra=A;
	while(p!=NULL)
	{
		ra->next=p;ra=p;
		p=p->next;
		q=p->next;
		p->next=B->next;
		B->next=p;
		p=q;
	}
	ra->next=NULL;
	return B;
}

void ShowList(LinkList L)
{
	LNode *p=L->next;
	while(p)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n");
}

void DestroyLinkList(LinkList &L)
{
	LNode* p;
	while(L)
	{
		p=L;
		L=L->next;
		free(p);
	}
	return;
}

int main()
{
	LinkList hc,A,B;
	
	printf("构造数量为偶数个的单链表hc:\n");
	hc=Link_TailInsert(hc);
	A=hc;
	
	//将单链表hc拆成A和B两个等长单链表: 
	B=DisCreate_2(A);
	
	printf("输出链表A的值:\n");
	ShowList(A);
	printf("输出链表B的值:\n");
	ShowList(B);
	
	DestroyLinkList(A);
	DestroyLinkList(B);
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值