Print Immutable Linked List in Reverse — LeetCode 1265 Python Solution

MediumLeetCode PremiumStackRecursionLinked ListTwo Pointers
Problem
#1265
Reading time
3 min

The problem

You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface: ImmutableListNode: An interface of immutable linked list, you are given the head of the list. You need to use the following functions to access the linked list (you can't access the ImmutableListNode directly): ImmutableListNode.printValue(): Print value of the current node.

Example

Input
head = [1,2,3,4]
Output
[4,3,2,1]

Python solution

Python
# """
# This is the ImmutableListNode's API interface.
# You should not implement it, or speculate about its implementation.
# """
# class ImmutableListNode:
#     def printValue(self) -> None: # print the value of this node.
#     def getNext(self) -> 'ImmutableListNode': # return the next node.


class Solution:
    def printLinkedListInReverse(self, head: 'ImmutableListNode') -> None:
        if head:
            self.printLinkedListInReverse(head.getNext())
            head.printValue()

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 1265. Print Immutable Linked List in Reverse is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1265. Print Immutable Linked List in Reverse?
LeetCode 1265. Print Immutable Linked List in Reverse is rated Medium on LeetCode.
What is the time complexity of LeetCode 1265. Print Immutable Linked List in Reverse?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1265. Print Immutable Linked List in Reverse?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1265. Print Immutable Linked List in Reverse cover?
LeetCode 1265. Print Immutable Linked List in Reverse is tagged Stack, Recursion, Linked List and Two Pointers on LeetCode.
Is LeetCode 1265. Print Immutable Linked List in Reverse a premium problem?
Yes. LeetCode 1265. Print Immutable Linked List in Reverse is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview