《数据结构与算法分析–C语言描述 2ed》第3章第3章表、栈和队列 课后习题

3.1 打印单链表的所有元素

void PrintList(const List L)
{
	Position P = Header(L);
	if (IsEmpty(L))
		printf("Empty List\n");
	else
	{
		do
		{
			P = Advance(P);//P->Next
			printf("%d ", Retrieve(P));//P->Element
		} while (!IsLast(P, L));
		printf("\n");
	}
}

3.2 链表P和L,均包含以升序排列的整数。PrintList(L,P)将打印出那些由P所指定的位置上的元素。

例如,如果P=1,3,4,6,那么,L中的第1、3、4、6个元素将被打印出来。
编写PrintList(L,P),只使用基本的链表操作,该程序的运行时间是多少?

void PrintList(List L, List P)
{
	int Counter = 1;
	Position Lpos = First(L), Ppos = First(P);
	while (Lpos != NULL && Ppos != NULL)
	{
		if(Ppos->Element == Counter++)
		{
			printf("%?", Lpos->Element);
			Ppos = next(Ppos, P);
		}
		Lpos = Next(Lpos, L);
	}
}

O(L+P)

3.3 通过调整指针来交换两个相邻的元素

a. 单链表

void SwapWithNext(Position BeforeP, List L)
{
	Position P = BeforeP->Next;
	Position AfterP = P->Next;

	P->Next = AfterP->Next;
	BeforeP->Next = AfterP;
	AfterP->Next = P;
}

b. 双链表

void SwapWithNext(Position P, List L)
{
	Position BeforeP = P->Prev;
	Position AfterP = P->Next;

	P->Next = AfterP->Next;
	BeforeP->Next = AfterP;
	AfterP->Next = P;

	P->Next->Prev = P;
	P->Prev = AfterP;
	AfterP->Prev = BeforeP;
}

3.4 给定两个已排序的链表L1和L2,只使用基本的链表操作编写计算L1 ∩ L2 的过程

List Intersect(List L1, List L2)
{
	List Result = MakeEmpty(NULL);
	Position L1Pos = First(L1);
	Position L2Pos = First(L2);
	Position ResultPos =First(Result);

	while (L1Pos != NULL && L2Pos != NULL)
	{
		if (L1Pos->Element < L2Pos->Element)
			L1Pos = Next(L1Pos, L1);
		else if (L1Pos->Element > L2Pos->Element)
			L2Pos = Next(L2Pos, L2);
		else
		{
			Insert(L1Pos->Element, Result, ResultPos);
			L1 = Next(L1Pos, L1);
			L2 = Next(L2Pos, L2);
			ResultPos = Next(ResultPos, Result);
		}
	}
	return Result;
}

3.5 给定两个已排序的链表L1和L2,只使用基本的链表操作编写计算L1 ∪ L2 的过程

continue 3.4 


发布了12 篇原创文章 · 获赞 10 · 访问量 7172

猜你喜欢

转载自blog.csdn.net/liangwenhao1108/article/details/104402866