可以利用栈的结构来存储,每经过一个结点的时候,把该结点放到一个栈当中去,当遍历完整个链表后,再从栈顶开始主格输出结点的值
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
void PrintListReversingly_Iteratively(ListNode* pHead)
{
std::stack<ListNode*> = pHead;
ListNode* pNode = pHead;
while(pNode != NULL)
{
nodes.push_back(pNode);
pNode = pNode->m_pNext;
}
while(!nodes.empty())
{
pNode = nodes.top();
cout<<pNode->m_nValue<<"-->";
nodes.pop();
}
cout<<endl;
}
由此可以想到使用递归的方法,我们每访问到一个结点的时候,先递归输出它后面的结点,再输出该结点本身,这样输出结果自然就反过来的。
void PrintListReversingly_Recursively(ListNode* pHead)
{
if(pHead != NULL)
{
if(pHead->m_pNext != NULL)
{
PrintListReversingly_Recursively(pHead->m_pNext);
}
cout<<pHead->m_nValue<<"-->";
}
}
当然递归会调用堆栈比较多,所以要根据情况来看使用递归还是栈