您的位置:首页 > 职场人生

面试题—— 从尾到头打印链表

2015-07-30 17:29 309 查看
链表结点定义如下:

struct ListNode
{
      int  m_nKey;
      ListNode*  m_pNext;
}


1.先将链表逆置, 然后遍历输出 ,但这样做会改变原链表的结构。

void reverseOutput(ListNode* pHead)
{
	if (pHead == NULL)
	{
		return;
	}
	ListNode* pPrior = NULL;
	ListNode* pNow = pHead;
	ListNode* pNext = pNow->m_pNext;

	while (pNow != NULL)
	{
		pNow->m_pNext = pPrior;
		pPrior = pNow;
		pNow = pNext;
        if (pNext!=NULL)
		{
			pNext = pNext->m_pNext;
        }
	}

        pHead = pPrior;
	pNow = pHead;
	while (pNow)
	{
		cout << pNow->m_nKey << " ";
		pNow = pNow->m_pNext;
	}
	
	cout << endl;
}


2.利用栈, 从头到尾遍历链表, 没遍历一个结点就进栈, 完成后输出栈顶值, 出栈, 直到栈空。

void reverseOutput(ListNode* pHead)
{
	if (pHead == NULL)
	{
		return;
	}
	std::stack<ListNode*> nodes;
	ListNode* pNode = pHead;
	while (pNode)
	{
		nodes.push(pNode);
		pNode = pNode->m_pNext;
	}
	
	while (!nodes.empty())
	{
		pNode = nodes.top();
		cout << pNode->m_nKey << " ";
		nodes.pop();
	}
	cout << endl;
}


3.递归, 每访问一个结点, 先输出它后面的结点, 再输出自深。 但如果链表非常长, 可能会爆栈。
void reverseOutput(ListNode* pHead)
{
	if ( pHead!=NULL )
	{
		if (pHead->m_pNext != NULL)
		{
			reverseOutput(pHead->m_pNext);
		}
		cout << pHead->m_nKey << " ";
		
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: