1265.逆序打印不可变链表
1265. 逆序打印不可变链表
示例 1:输入:head = [1,2,3,4]
输出:[4,3,2,1]
示例 2:
输入:head = [0,-4,-1,3,-5]
输出:[-5,3,-1,-4,0]
正向遍历列表:
cur = headwhile cur:
cur.printValue()
cur = cur.getNext()
思路
- 递归调用,参考dfs
- 先递归,后打印
使用栈:
顺序入栈,出栈完成反向
代码
# """# 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 dfs(self, cur: "ImmutableListNode"):
if not cur:
return
next_node = cur.getNext()
self.dfs(next_node)
cur.printValue()
def printLinkedListInReverse(self, head: "ImmutableListNode") -> None:
self.dfs(head)
以上是 1265.逆序打印不可变链表 的全部内容, 来源链接: utcz.com/z/518846.html