《剑指offer》面试题5—从尾到头打印链表
2013-09-07 19:27
651 查看
重要思路:
这个问题肯定要遍历链表,遍历链表的顺序是从头到尾,而要输出的顺序却是从尾到头,典型的“后进先出”,可以用栈实现。
注意stl栈的使用,遍历stack的方法。
View Code
这个问题肯定要遍历链表,遍历链表的顺序是从头到尾,而要输出的顺序却是从尾到头,典型的“后进先出”,可以用栈实现。
注意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
相关文章推荐
- 剑指offer面试题5——链表之从尾到头打印链表
- 《剑指Offer》学习笔记--面试题5:从尾到头打印链表
- 剑指offer《面试题5:从尾到头打印链表》
- 剑指Offer系列-面试题5:从尾到头打印链表
- 《剑指Offer》面试题:从尾到头打印链表
- 《剑指Offer》面试题五之从尾到头打印链表
- 剑指Offer面试题5(Java版):从尾到头打印链表
- 剑指Offer面试题6:从尾到头打印链表
- 剑指offer面试题5:从尾到头打印链表
- 剑指offer——面试题5:从尾到头打印链表
- 《剑指offer》Python语言 面试题5:从尾到头打印链表
- 剑指offer 面试题5 从尾到头打印链表(栈实现)
- 剑指offer--面试题5:从尾到头打印链表--Java实现
- 剑指offer--面试题5:从尾到头打印链表
- 《剑指offer》面试题5:从尾到头打印链表
- 剑指Offer(第二版)面试题6:从尾到头打印链表
- 剑指offer面试题6-从尾到头打印链表-java
- 剑指Offer: 面试题5 从尾到头打印链表
- 剑指offer之面试题5:从尾到头打印链表
- 剑指Offer学习之面试题5 : 从尾到头打印链表