前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 1265. 逆序打印不可变链表(递归)

LeetCode 1265. 逆序打印不可变链表(递归)

作者头像
Michael阿明
发布2020-07-13 16:18:50
6710
发布2020-07-13 16:18:50
举报

1. 题目

给您一个不可变的链表,使用下列接口逆序打印每个节点的值:

  • ImmutableListNode: 描述不可变链表的接口,链表的头节点已给出。

您需要使用以下函数来访问此链表(您 不能 直接访问 ImmutableListNode):

  • ImmutableListNode.printValue():打印当前节点的值。
  • ImmutableListNode.getNext():返回下一个节点。

输入只用来内部初始化链表。您不可以通过修改链表解决问题。 也就是说,您只能通过上述 API 来操作链表。

进阶: 您是否可以: 使用常数级空间复杂度解决问题? 使用线性级时间复杂度和低于线性级空间复杂度解决问题?

代码语言:javascript
复制
示例 1:
输入:head = [1,2,3,4]
输出:[4,3,2,1]

示例 2:
输入:head = [0,-4,-1,3,-5]
输出:[-5,3,-1,-4,0]

示例 3:
输入:head = [-2,0,6,4,4,-6]
输出:[-6,4,4,6,0,-2]
 
提示:
链表的长度在 [1, 1000] 之间。
每个节点的值在 [-1000, 1000] 之间。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/print-immutable-linked-list-in-reverse 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

代码语言:javascript
复制
/**
 * // This is the ImmutableListNode's API interface.
 * // You should not implement it, or speculate about its implementation.
 * class ImmutableListNode {
 * public:
 *    void printValue(); // print the value of the node.
 *    ImmutableListNode* getNext(); // return the next node.
 * };
 */

class Solution {//C++
public:
    void printLinkedListInReverse(ImmutableListNode* head) {
        if(!head)
        	return;
        printLinkedListInReverse(head->getNext());
        head->printValue();
    }
};

0 ms 6.8 MB

代码语言:javascript
复制
# """
# 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: # py3
    def printLinkedListInReverse(self, head: 'ImmutableListNode') -> None:
        if not head:
        	return
        self.printLinkedListInReverse(head.getNext())
        head.printValue()

56 ms 14.3 MB

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-07-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档