查找单链表到时第四个元素

//查找单链表到时第四个元素

#include <iostream>
using namespace std;

struct LinkNode
{
	LinkNode *pNext;
	int nValue;
	LinkNode(int value = 0)
	{
		nValue = value;
		pNext = NULL;
	}
};

class Linklist
{
public:
	Linklist(){ pHead = new LinkNode(); };
	~Linklist(){ delete pHead;}; 
	void InsertValue(int nValue);
	void Reverse();
	void Reverse2();
	LinkNode *FindLastNum(int nNum);
	void Print();

private:
	LinkNode *pHead;
};


void Linklist::InsertValue(int nValue)
{
	if (pHead == NULL)
	{
		return;
	}
	LinkNode *pCur = pHead;
	while (pCur->pNext != NULL)
	{
		pCur = pCur->pNext;
	}

	LinkNode *pTmp = new LinkNode(nValue);
	pCur->pNext = pTmp;
}

void Linklist::Reverse()
{
	if (pHead == NULL)
	{
		return;
	}

	//特殊情况:如果链表为空或者只有一个元素,直接返回
	if (pHead->pNext == NULL || pHead->pNext->pNext == NULL)
	{
		return;
	}

	LinkNode *pPre = pHead;
	LinkNode *pCur = pHead->pNext;
	LinkNode *pNext;
	
	while (pCur != NULL)
	{
		pNext = pCur->pNext;
		pCur->pNext = pPre;
		pPre = pCur;
		pCur = pNext;
	}
	
	pHead->pNext->pNext = NULL;
	pHead->pNext = pPre;
}

void Linklist::Reverse2()
{
	if (pHead == NULL)
	{
		return;
	}

	//特殊情况:如果链表为空或者只有一个元素,直接返回
	if (pHead->pNext == NULL || pHead->pNext->pNext == NULL)
	{
		return;
	}

	LinkNode *pCur = pHead->pNext;
	LinkNode *pNext = NULL;
	LinkNode *pNextNext = NULL;
	
	while (pCur->pNext != NULL)
	{
		pNext = pCur->pNext;
		pNextNext = pNext->pNext;
		
		pNext->pNext = pHead->pNext;
		pHead->pNext = pNext;
		pCur->pNext = pNextNext;
	}
}

LinkNode *Linklist::FindLastNum(int nNum)
{
	if (pHead == NULL)
	{
		return NULL;
	}
	LinkNode *pFirst = pHead;
	int i = 0;
	while (i < nNum)
	{
		if (pFirst == NULL)
		{
			return NULL;
		}
		pFirst = pFirst->pNext;
		i++;
	}
	LinkNode *pSecond = pHead;
	while (pFirst != NULL)
	{
		pFirst = pFirst->pNext;
		pSecond = pSecond->pNext;
	}

	return pSecond;
}
void Linklist::Print()
{
	if (pHead == NULL)
	{
		return;
	}
	LinkNode *pCur = pHead->pNext;
	while (pCur != NULL)
	{
		cout<<pCur->nValue<<" ";
		pCur = pCur->pNext;
	}
	cout<<endl;
}

int main()
{
	Linklist list;
	int nArr[] = {12,13,43,1,2,4,55,32};
	for (int i = 0; i < 8; i++)
	{
		list.InsertValue(nArr[i]);
	}
	list.Print();
	
	LinkNode *pFind = list.FindLastNum(7);
	if (pFind != NULL)
	{
		cout<<pFind->nValue<<endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值