您的位置:首页 > 其它

每日一题(11) - 统计有环单链表的环中结点个数

2013-06-22 15:51 267 查看
题目来自编程之美

题目:统计有环单链表的环中结点个数

思路:参考单链表面试题

代码

/*思路:在快慢指针相遇位置肯定是在环中,此时一个指针不动,让另一个指针转圈,再次相遇时经过的结点个数就是环中结点个数*/
int GetCountOfCycle(ListNode* pHead)
{
	assert(pHead != NULL);
	ListNode* pFast = pHead;
	ListNode* pSlow = pHead;
	int nCount = 1;//第一个结点是相遇点

	while (pFast->m_pNext && pFast->m_pNext->m_pNext)
	{
		pFast = pFast->m_pNext->m_pNext;
		pSlow = pSlow->m_pNext;
		if (pFast == pSlow)//碰撞点
		{
			//计算环中结点个数
			pFast = pFast->m_pNext;
			while (pFast != pSlow)
			{
				nCount++;
				pFast = pFast->m_pNext;
			}
			return nCount;
		}
	}
	return 0;
}
测试代码

#include <iostream>
#include <assert.h>
using namespace std;

struct ListNode
{
int m_Data;
ListNode* m_pNext;
};

bool IsCycle(ListNode* pHead)
{
assert(pHead != NULL);
ListNode* pFast = pHead;
ListNode* pSlow = pHead;
while (pFast->m_pNext && pFast->m_pNext->m_pNext)
{
pFast = pFast->m_pNext->m_pNext;
pSlow = pSlow->m_pNext;
if (pFast == pSlow)
{
return true;
}
}
return false;
}

/*思路:在快慢指针相遇位置肯定是在环中,此时一个指针不动,让另一个指针转圈,再次相遇时经过的结点个数就是环中结点个数*/ int GetCountOfCycle(ListNode* pHead) { assert(pHead != NULL); ListNode* pFast = pHead; ListNode* pSlow = pHead; int nCount = 1;//第一个结点是相遇点 while (pFast->m_pNext && pFast->m_pNext->m_pNext) { pFast = pFast->m_pNext->m_pNext; pSlow = pSlow->m_pNext; if (pFast == pSlow)//碰撞点 { //计算环中结点个数 pFast = pFast->m_pNext; while (pFast != pSlow) { nCount++; pFast = pFast->m_pNext; } return nCount; } } return 0; }
void CreateList(ListNode** pHead,int nLen)//头指针使用指针的指针
{
assert(*pHead == NULL && nLen > 0);
ListNode* pCur = NULL;
ListNode* pNewNode = NULL;
for (int i = 0;i < nLen;i++)
{
pNewNode = new ListNode;
cin>>pNewNode->m_Data;
pNewNode->m_pNext = NULL;

if (*pHead == NULL)
{
*pHead = pNewNode;
pCur = *pHead;
}
else
{
pCur->m_pNext = pNewNode;
pCur = pNewNode;
}
}
}

/*把链表最后一个结点指向第三个结点*/
void CreateCycle(ListNode* pHead)
{
assert(pHead);
ListNode* pLastNode = pHead;
while (pLastNode->m_pNext)
{
pLastNode = pLastNode->m_pNext;
}
if (pHead->m_pNext && pHead->m_pNext->m_pNext)
{
pLastNode->m_pNext = pHead->m_pNext->m_pNext;
}
}

int main()
{
int nLen = 0;
bool bIsCircle = false;
ListNode* pHead = NULL;
ListNode* pHeadSec = NULL;
ListNode* pEntry = NULL;

cout<<"please input node num: ";
cin >> nLen;
CreateList(&pHead,nLen);//注意传参使用引用
CreateCycle(pHead);
bIsCircle = IsCycle(pHead);
if (bIsCircle)
{
cout<<"有环!"<<endl;
cout<<"环中结点个数: "<<GetCountOfCycle(pHead)<<endl;
}
else
{
cout<<"无环"<<endl;
}

cout<<"please input node num: ";
cin >> nLen;
CreateList(&pHeadSec,nLen);//注意传参使用引用
CreateCycle(pHeadSec);
bIsCircle = IsCycle(pHeadSec);
if (bIsCircle)
{
cout<<"有环!"<<endl;
cout<<"环中结点个数: "<<GetCountOfCycle(pHeadSec)<<endl;
}
else
{
cout<<"无环"<<endl;
}

system("pause");
return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐