题目:
输入一个链表的头结点,从尾到头反过来打印出每一个节点的值。
分析:
后进先出,可以用栈来实现。
代码:
链表结点定义如下:
struct ListNode { int m_nKey; ListNode *m_pNext; };
实现代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
void PrintListReverse(ListNode
*pHead) { std::stack<ListNode*>
nodes;//栈,用来存放遍历到的结点 ListNode
*pNode = pHead; while (pNode
!= NULL) { nodes.push(pNode);//入栈 pNode
= pNode->m_pNext; } while (!nodes.empty()) { pNode
= nodes.top(); printf ( "%d\t" ,
pNode->m_nValue); nodes.pop();//出栈 } } |
void
PrintListReversely(ListNode*
pListHead) //当访问一个结点是,先递归输出它后面的结点,在输出该结点本身。
{
if
(pListHead
!= NULL)
{
//
Print the next node first
if
(pListHead->m_pNext
!= NULL)
{
PrintListReversely(pListHead->m_pNext);
}
//
Print this node
printf
(
"%d"
,
pListHead->m_nKey);
}
}