题目
从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例
输入:head = [1,3,2]
输出:[2,3,1]
题解一(栈):
解法:遍历链表,将所有遍历到的值压入栈中,再利用栈“后进先出”的特性,从尾到头打印链表
时间复杂度O(n),空间复杂度O(n)
python3:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 利用list实现类似栈先入后出的功能
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
stack = []
while head:
stack.append(head.val)
head = head.next
return stack[::-1]
C++:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// std::stack<ListNode*>nodes;参数ListNode*指定了存储对象的类型,参数nodes制定了底层容器的类型
// std::vector<int>data,利用了标准库vector(与返回值类型相同),制定了容器名data的数据类型为int
// vector::push_back,添加元素到vector末尾
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int> s;
vector<int> res;
ListNode* pre=head;
while(pre){
s.push(pre->val);
pre=pre->next;
}
while(!s.empty()){
res.push_back(s.top());
s.pop();
}
return res;
}
};
};
题解二(递归):
解法:递归的本质是一个栈结构,每访问到一个结点的时候,先递归输出它后面的节点,再输出该节点自身,这样链表的输出结果就反过来了
时间复杂度O(n),空间复杂度O(n)
python3:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 递推阶段: 每次传入 head.next ,以 head == None(即走过链表尾部节点)为递归终止条件,此时返回空列表 [] 。
#回溯阶段: 利用 Python 语言特性,递归回溯时每次返回 当前 list + 当前节点值 [head.val] ,即可实现节点的倒序输出。
# 递归会导致调用的层级很深,时间和内存损耗较大
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
return self.reversePrint(head.next) + [head.val] if head else []
C++:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// 递归法,要实现反过来输出链表,每访问到一个节点,先输出后面的节点,在输出该节点自身
// vector::push_back,添加元素到vector末尾
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
if(!head)
return {};
vector<int> a = reversePrint(head->next);
a.push_back(head->val);
return a;
}
};