从尾到头打印链表
题目描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
来源:力扣(leetcode)
链接:从尾到头打印链表
题记:
从尾到头,第一想到的数据结构应该是栈,栈的特点是先入后出,所以先来复习一下栈的基本操作:
操作 | 描述 |
---|---|
s.empty() | 如果栈为空返回true,否则返回false |
s.size() | 返回栈中元素的个数 |
s.pop() | 删除栈顶元素但不返回其值 |
s.top() | 返回栈顶的元素,但不删除该元素 |
s.push(x) | 在栈顶压入新元素x |
针对本题,我们可以先将链表元素一次压入栈中,再将元素逐个取出放入数组即可,C++代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
if (!head){
return {};
}
stack <int> stk;
vector <int> res;
while(head){
stk.push(head->val);
head = head->next;
}
while(!stk.empty()){
res.push_back(stk.top());
stk.pop();
}
return res;
}
};
想到了栈必然想到递归,其实递归的实现本质是依靠栈的:
递归Python代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
if not head:
return []
return self.reversePrint(head.next)+[head.val]
递归C++代码:
class Solution:{
public:
vector<int>res;
vector<int> reversePrint(ListNode* head) {
if (!head){
return res;
}
reversePrint(head->next);
res.push_back(head->val);
return res;
}
};