剑指offer 面试题5

来源:互联网 发布:什么是数组 编辑:程序博客网 时间:2024/06/08 08:53

从尾到头打印出每一个结点的值

题目:
输入一个链表的头结点,从尾到头反过来打印出每个结点的值。

说明:
本题要求不能破坏原本的数据结构。

#include<iostream>#include<stack>using namespace std;struct ListNode{    int m_nKey;    ListNode *m_pNext;};void PrintListReverse(ListNode *pHead){    if (NULL == pHead)        return;    stack<ListNode*>nodes;    ListNode *p = pHead;    while (NULL != p)    {        nodes.push(p);        p = p->m_pNext;    }    while (!nodes.empty())    {        p = nodes.top();        cout << p->m_nKey << " ";        nodes.pop();    }}int main(){    int i = 0;    ListNode *p = NULL;    while (i < 10)    {        ListNode *temp = new ListNode;        temp->m_nKey = i++;        temp->m_pNext = p;        p = temp;    }    PrintListReverse(p);    return 0;}//.......................通过递归实现void PrintListReverse(ListNode *pHead){    if (NULL == pHead)        return;    if (NULL == pHead->m_pNext)        cout << pHead->m_nKey << " ";    else    {        PrintListReverse(pHead->m_pNext);        cout << pHead->m_nKey << " ";    }}
1 0