数据结构习题(2):单链表

2 篇文章 0 订阅
2 篇文章 0 订阅

1.寻找单链表倒数第K个节点。

Node* find_k(PLink phead, int k)
{
	Node* pfast = phead->pnext;
	Node* pslow = pfast;

	for (int i = 0; i < k - 1; ++i)
	{
		pfast = pfast->pnext;
	}
	while (pfast->pnext != NULL)
	{
		pfast = pfast->pnext;
		pslow = pslow->pnext;
	}
	return pslow;
}

2.只给定单链表的某个节点P,
p不是尾结点(//p->next != NULL),删除该节点

void DeletePoint(Node* pCur)
{
	Node* pDelete = pCur->pnext;
	pCur->mdata = pDelete->mdata;

	pCur->pnext = pDelete->pnext;
	free(pDelete);
}

3.单链表只给定一个节点p,在p之前插入一个数据val。

 

int InsertFront(Node* p, ELEM_TYPE val)
{
	Node* pnewnode = (Node*)malloc(sizeof(Node));
	if (pnewnode == NULL)
	{
		return 0;
	}
	pnewnode->pnext = p->pnext;
	p->pnext = pnewnode;

	pnewnode->mdata = p->mdata;
	p->mdata = val;
	return 1;
}

 4.判断两个链表是否相交,如果相交,找出交点

Node* Intersect(PLink phead1, PLink phead2)
{
	Node* pCur1 = phead1;
	Node* pCur2 = phead2;
	int len1 = 0;
	int len2 = 0;
	while (pCur1->pnext != NULL)
	{
		pCur1 = pCur1->pnext;
		len1++;
	}
	while (pCur2->pnext != NULL)
	{
		pCur2 = pCur2->pnext;
		len2++;
	}
	if (pCur1 == pCur1)
	{
		int k = abs(len1 - len2);
		pCur1 = (len1 - len2) > 0 ? phead1 : phead2;
		pCur2 = (len1 - len2) <= 0 ? phead1 : phead2;
		for (int i = 0; i < k; ++i)
		{
			pCur1 = pCur1->pnext;
		}
		while (pCur1 != NULL)
		{
			if (pCur1 == pCur2)
			{
				return pCur1;
			}
			pCur1 = pCur1->pnext;
			pCur2 = pCur2->pnext;
		}
	}
	return NULL;
}

 5.找单链表的中间节点,只允许遍历一次。

Node* Find_Middle_Node(PLink phead)
{
	Node* pfast = phead->pnext;
	Node* pslow = pfast;

	while (pfast != NULL && pfast->pnext != NULL)
	{
		pfast = pfast->pnext->pnext;
		pslow = pslow->pnext;
	}
	return pslow;
}

6.从尾到头打印单链表 
 1.不能破坏单链表结构
 2.不能使用栈
(递归)

void PrintR(PLink node)
{
	if (node == NULL)
	{
		return;
	}
	PrintR(node->pnext);
	printf("%d ", node->mdata);
}
void PrintReverse(PLink phead)
{
	Node* pfirst = phead->pnext;
	PrintR(pfirst);
	printf("\n");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值