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

《剑指offer》面试题5—从尾到头打印链表

2013-09-07 19:27 651 查看
重要思路:

这个问题肯定要遍历链表,遍历链表的顺序是从头到尾,而要输出的顺序却是从尾到头,典型的“后进先出”,可以用栈实现。

注意stl栈的使用,遍历stack的方法。

#include <iostream>
#include <stack>
using namespace std;

class Node
{
public:
Node(int v, Node* n)
{val = v;
next = n;}
~Node(){}
int val;
Node* next;
};
Node * phead = NULL;

void AddNode(int val)
{
Node* pnode = new Node(val,NULL);
//Node one_node(val,NULL); 这里有大bug!如果这样写,在函数退出时自动调用析构函数!链表就乱了!
if(phead == NULL)
{
phead = pnode;
}
else
{
Node* p = phead;
while(p->next != NULL)
{
p = p->next;
}
p->next = pnode;
}
}
void PrintLink()
{
Node* p = phead;
while(p != NULL)
{
int temp = p->val;
cout<<temp<<endl;
p = p->next;
}
}
void PrintLinkReverse()
{
stack<Node*> my_s;
Node* p = phead;
while(p != NULL)
{
my_s.push(p);
p = p->next;
}
while(!my_s.empty())
{
Node* temp = my_s.top();   //return the top value
cout<<temp->val<<endl;
my_s.pop();  //delete the top value, no return

}
}

int main()
{
//freopen("in.txt","r",stdin);
int val;
cin>>val;
while(val != 0)
{
AddNode(val);
cin>>val;
}
PrintLink();
cout<<"Reverse:"<<endl;
PrintLinkReverse();
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: