题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值
链表的结点定义如下:
struct ListNode
{
int m_nkey;
ListNode* m_pNext;
};
//基于循环----用栈来实现
void PrintListReversingly_Iteratively(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();
}
cout<<endl;
}
//用递归来实现
void PrintListReversingly_Iteratively(ListNode* pHead)
{
ListNode* pnode = pHead;
if(pnode != NULL)
{
if(pnode->m_pNext != NULL)
{
PrintListReversingly_Iteratively(pnode->m_pNext);
}
cout<<pnode->m_nkey<<" ";
}
}