链表结点定义如下:
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;
}
void reverseOutput(ListNode* pHead)
{
if ( pHead!=NULL )
{
if (pHead->m_pNext != NULL)
{
reverseOutput(pHead->m_pNext);
}
cout << pHead->m_nKey << " ";
}
}