【剑指 Offer 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

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

解析思路 3: 反转

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

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> 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。

Guess you like

Origin blog.csdn.net/Kefenggewu_/article/details/121125952