06. 从尾到头打印链表
来源:力扣(LeetCode)
链接: https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
解题思路:
- 单链表的方向是单向的,且题目要求是从尾到头打印链表,则类似于先进后出的样式,考虑使用栈这一数据结构,当遍历完单链表后,所有节点都入栈,之后再出栈即为逆序。
代码实现
- 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 head is None:
return []
stack = []
cur = head
while cur:
stack.append(cur.val)
cur = cur.next
result = []
while stack:
result.append(stack.pop())
return result
- 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> result;
stack<int> st;
ListNode* cur = head;
// 入栈
while(cur != NULL)
{
st.push(cur->val);
cur = cur->next;
}
// 出栈
while(!st.empty())
{
result.push_back(st.top());
st.pop();
}
return result;
}
};
复杂度分析
- 时间复杂度: O ( N ) O(N) O(N)
- 空间复杂度: O ( N ) O(N) O(N)
使用栈解决从尾到头打印链表问题
本文介绍了如何利用栈数据结构解决LeetCode中的一道题目——从尾到头打印链表。通过遍历链表将节点值依次入栈,然后出栈,可以实现链表的逆序打印。代码分别给出了Python和C++两种实现方式,时间复杂度和空间复杂度均为O(N)。
796

被折叠的 条评论
为什么被折叠?



