当前位置: 代码迷 >> 综合 >> 从尾到头打印链表(简单)
  详细解决方案

从尾到头打印链表(简单)

热度:41   发布时间:2024-03-08 14:07:21.0

从尾到头打印链表(简单)

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

#include<vector>
#include<stack>
using namespace std;struct ListNode
{int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:vector<int> reversePrint(ListNode* head){vector<int> res;stack<int> s;while(head){s.push(head->val);head = head->next;}while(!s.empty()){res.push_back(s.top());s.pop();}return res;}
};
  • 方法:从头到尾遍历原始链表,用栈来保存,最后弹出到向量中。
  • 知识点:
  1. using namespace std;C++标准程序库中的所有标识符都被定义与一个名为std的namespace中;
  2. s.push()在栈顶增加元素;
  3. res.push_back()将一个新的元素加到vector最后面;
  4. s.top()返回栈顶元素,但不会删除栈里面的元素;
  5. s.pop()移除栈顶元素;
  相关解决方案