Print Immutable Linked List in Reverse — LeetCode 1265 Python Solution
- Problem
- #1265
- Pattern
- Linked List
- Reading time
- 3 min
- Source
- leetcode.com
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
# """
# 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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.