【剑指 Offer 06】从尾到头打印链表

【剑指 Offer 06】从尾到头打印链表,第1张

【剑指 Offer 06】从尾到头打印链表

【剑指 Offer 06】从尾到头打印链表
    • 题目描述:
    • 示例:
    • 解析思路 1: 使用 栈 stack
    • 解析思路 2: 使用 递归
    • 解析思路 3: 反转

题目描述:

来源:力扣(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
解析思路 1: 使用 栈 stack

(香辣鸡排蛋包饭讲解图)

  • 代码(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]:
        stack  = [];
        while head:  #(入栈)
            stack.append(head.val);
            head = head.next
        return stack[::-1]   # (反向出栈)
      # res = [];
      # while stack:  # (出栈)
      #    res.append(stack.pop())
      # return res

  • 代码(c++)
class Solution {
public:
    vector res;
    vector reversePrint(ListNode* head) {
        stack st;
        while(head){// push
            st.push(head->val);
            head = head->next;
        }
        while(!st.empty()){ // pop
            res.push_back(st.top());
            st.pop();
        }
        return res;
    }
};

  • 复杂度分析
  • 时间复杂度:O(n),push 的间复杂度为O(n),pop 的间复杂度为 O(n)。
  • 空间复杂度:O(n),使用了额外的 res 和 堆栈。
解析思路 2: 使用 递归

(香辣鸡排蛋包饭讲解图)

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 res;
    vector reversePrint(ListNode* head) {
        if (!head) return res;
        reversePrint(head->next);
        res.push_back(head->val);
        return res;
    }
};

解析思路 3: 反转
  • 从头到尾将链表打印到数组中,返回反转后的结果即可。

c++


class Solution {
public:
    vector reversePrint(ListNode* head) {
        vector res;
        while (head){ // 入栈
            res.push_back(head->val);
            head = head->next;
            
        }
        reverse(res.begin(),res.end());  // 反向输出容器
        return res;
    }
};

python

class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        res = []
        while head:
            res.append(head.val)
            head = head.next
        return res[::-1]  # 或者 reverse(res)


复杂度分析

  • 时间复杂度:O(n),reverse() 的时间复杂度为O(n),遍历了一遍数组,复杂度也为 O(n)。
  • 空间复杂度:O(n),使用了额外的 res。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5116064.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-17
下一篇2022-11-17

发表评论

登录后才能评论

评论列表(0条)

    保存