典型的后进先出,可以用栈实现这种顺序,每经过一个节点的时候,把该节点放到栈中,当遍历完整个链表后,再从栈顶开始逐个输出节点的值。
#include<iostream>
#include<stack>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode *m_pNext;
};
void AddToTail(ListNode** pHead,int value)
{
ListNode* pNew = new ListNode();
pNew->m_nKey = value;
pNew->m_pNext = NULL;
if (*pHead == NULL)
*pHead = pNew;
else
{
ListNode* pNode = *pHead;
while (pNode->m_pNext != NULL)
pNode = pNode->m_pNext;
pNode->m_pNext = pNew;
}
}
void RemoveNode(ListNode** pHead, int value)
{
if (pHead == NULL || *pHead == NULL)
return;
ListNode* pToBeDeleted = NULL;
if ((*pHead)->m_nKey == value)
{
pToBeDeleted = *pHead;
*pHead = (*pHead)->m_pNext;
}
else
{
ListNode* pNode = *pHead;
while (pNode->m_pNext != NULL && pNode->m_pNext->m_nKey != value)
pNode = pNode->m_pNext;
if (pNode->m_pNext != NULL&&pNode->m_pNext->m_nKey == value)
{
pToBeDeleted = pNode->m_pNext;
pNode->m_pNext = pNode->m_pNext->m_pNext;
}
}
if (pToBeDeleted != NULL)
{
delete pToBeDeleted;
pToBeDeleted = NULL;
}
}
void PrintListReverse(ListNode* pHead)
{
stack<ListNode*> nodes;
ListNode* pNode = pHead;
while (pNode != NULL)
{
nodes.push(pNode);
pNode = pNode->m_pNext;
}
while (!nodes.empty())
{
pNode = nodes.top();
cout << pNode->m_nKey << " ";
nodes.pop();
}
}
int main()
{
ListNode* pHead = NULL;
for (int i = 0; i < 10;i++)
AddToTail(&pHead, i);
PrintListReverse(pHead);
}