剑指 Offer 06. 从尾到头打印链表
题目链接
这道题看到逆序打印,可以很快想到用递归,递归使用系统内存中的栈,不断调用函数速度有点慢,自己用栈保存是更快的。
python版本:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def recurse(self, head: ListNode, ans: List[int]) -> List[int]:
if head == None:
return ans
self.recurse(head.next, ans)
ans.append(head.val)
return ans
def reversePrint(self, head: ListNode) -> List[int]:
return self.recurse(head, [])
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) {
vector<int> ans;
stack<int> s;
while(head)
{
s.push(head->val);
head = head->next;
}
while(s.size())
{
ans.push_back(s.top());
s.pop();
}
return ans;
}
};
如果对你有帮助的话,请点个赞哦!