您的位置:首页 > Web前端

剑指offer 从尾到头打印列表 包含vector 一些操作

2017-03-23 09:05 316 查看



剑指offer 从尾到头打印列表 包含vector 一些操作


题目描述

输入一个链表,从尾到头打印链表每个节点的值。

原理简单,先把链表存到栈中,然后再出栈。

看代码:

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

struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {

stack<ListNode*> s;

ListNode *pNode = head;
while(pNode != NULL){
s.push(pNode);
pNode = pNode->next;
}

vector<int> v;
while(!s.empty()){
v.push_back(s.top()->val); // 放入vector
s.pop();
}
return v;
}
};
int main(){
ListNode* a = new ListNode(1);
ListNode* b = new ListNode(2);
ListNode* c = new ListNode(3);
a->next = b;
b->next = c;
c->next = NULL;
Solution s;
vector<int> v = s.printListFromTailToHead(a);
for(int i = 0; i < v.size(); i++){
cout<<v[i]<<" "; //打印 vector
}

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