王道p40 11.C={a1,b1,a2,b2,...,an,bn}为线性表,采用带头结点的单链表存放,设计一个就地算法,将其拆分为两个线性表,使得A={a1..an},B={bn,.,b1

本题A链表应用尾插法,B链表应用头插法

linklist chaifen(linklist* L)//A链表用尾插法,B链表用头插法
{
	lnode* B = (lnode*)malloc(sizeof(lnode));
	B->next = NULL;
	lnode* p = (*L)->next, * ra = *L, * q;//p为工作指针,ra始终指向A的为结点
	while (p != NULL)
	{
		ra->next = p;
		ra = p;//将*p链接到A的表尾
		p = p->next;
		if (p != NULL)
		{
			q = p->next;//用q记录p的后继
			p->next = B->next;//将*p插入到B的前端
			B->next = p;
			p = q;
		}
	}
	ra->next = NULL;//A为结点的next域置空
	return B;
}

完整测试代码

#include
#include
typedef struct lnode
{
	int data;
	struct lnode* next;
}lnode,*linklist;
int n = 6;
int a[6] = { 1,2,3,4,5,6 };
void buildlinklist(linklist* L)
{
	*L = (lnode*)malloc(sizeof(lnode));
	(*L)->next = NULL;
	int i = 0;
	lnode* s = *L, * r = *L;
	for (i = 0; i < n; i++)
	{
		s = (lnode*)malloc(sizeof(lnode));
		s->data = a[i];
		s->next = r->next;
		r->next = s;
		r = s;
	}
	r->next = NULL;
}
linklist chaifen(linklist* L)//A链表用尾插法,B链表用头插法
{
	lnode* B = (lnode*)malloc(sizeof(lnode));
	B->next = NULL;
	lnode* p = (*L)->next, * ra = *L, * q;//p为工作指针,ra始终指向A的为结点
	while (p != NULL)
	{
		ra->next = p;
		ra = p;//将*p链接到A的表尾
		p = p->next;
		if (p != NULL)
		{
			q = p->next;//用q记录p的后继
			p->next = B->next;//将*p插入到B的前端
			B->next = p;
			p = q;
		}
	}
	ra->next = NULL;//A为结点的next域置空
	return B;
}
void print(linklist* L)//输出单链表
{
	lnode* k = (*L)->next;
	while (k)
	{
		printf("%d ", k->data);
		k = k->next;
	}
}
int main()
{
	linklist L, B;
	buildlinklist(&L);
	printf("原始单链表为:");
	print(&L);
	B = chaifen(&L);
	printf("\nA链表为:");
	print(&L);
	printf("\nB链表为:");
	print(&B);
	return 0;
}

你可能感兴趣的:(王道课后习题单链表,c语言,算法,数据结构)