LeetCode 1265. 逆序打印不可变链表
题目描述
给您一个不可变的链表,使用下列接口逆序打印每个节点的值:ImmutableListNode: 描述不可变链表的接口,链表的头节点已给出。您需要使用以下函数来访问此链表(您 不能 直接访问 ImmutableListNode):ImmutableListNode.printValue():打印当前节点的值。
ImmutableListNode.getNext():返回下一个节点。
输入只用来内部初始化链表。您不可以通过修改链表解决问题。也就是说,您只能通过上述 API 来操作链表。
示例 1:
输入:head = [1,2,3,4]
输出:[4,3,2,1]
链表的长度在 [1, 1000] 之间。
每个节点的值在 [-1000, 1000] 之间。
一、解题关键词
二、解题报告
1.思路分析
2.时间复杂度
3.代码示例
/**
* // This is the ImmutableListNode's API interface.
* // You should not implement it, or speculate about its implementation.
* interface ImmutableListNode {
* public void printValue(); // print the value of this node.
* public ImmutableListNode getNext(); // return the next node.
* };
*/
class Solution {
public void printLinkedListInReverse(ImmutableListNode head) {
part(head,null);
}
void part(ImmutableListNode start,ImmutableListNode end){
if(start.getNext() == end){
start.printValue();
return;
}
//快慢指针 找到中间节点
ImmutableListNode mid;
ImmutableListNode p = start,q = start;
while(true){
p = p.getNext();
q = q.getNext().getNext();
if(q == end || q.getNext() == end){
mid = p;
break;
}
}
//逆序 递归后半部分
part(mid,end);
part(start,mid);
}
}
2.知识点