您的位置:首页 > 职场人生

[剑指offer][面试题5]从尾到头打印链表

2013-10-10 18:06 429 查看
#include <iostream>
#include <stack>
using namespace std;

struct Node{
int   m_Data;
Node *m_pNext;
};

void printReverseList_Recursive(Node *pHead)
{
if (pHead){
printReverseList_Recursive(pHead->m_pNext);
cout<<pHead->m_Data<<"->";
}
}

void printReverseList_Iterative(Node *pHead)
{
if (pHead==NULL){
return;
}

stack<int> s;
while (pHead){
s.push(pHead->m_Data);
pHead = pHead->m_pNext;
}

while (!s.empty()){
cout<<s.top()<<"->";
s.pop();
}
cout<<"NULL"<<endl;
}

int main()
{
Node node5 = {5, NULL};
Node node4 = {4, &node5};
Node node3 = {3, &node4};
Node node2 = {2, &node3};
Node node1 = {1, &node2};
Node node0 = {0, &node1};
Node *pHead = &node0;
Node *pHead1 = &node0;

//print list
cout<<"Linked List: "<<endl;
while (pHead1){
cout<<pHead1->m_Data<<"->";
pHead1 = pHead1->m_pNext;
}
cout<<"NULL"<<endl;

//print list from tail to head
cout<<"Reverse Order (Recursive): "<<endl;
printReverseList_Recursive(pHead);
cout<<"NULL"<<endl;

//print list from tail to head
cout<<"Reverse Order (Iterative): "<<endl;
printReverseList_Iterative(pHead);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: