05 August 2008
给你一个不可变的链表,在下面的界面的帮助下,反向打印出每个节点的所有值:
ImmutableListNode:不可变链表的接口,给你链表的头部。
访问链表需要使用以下函数(不能直接访问ImmutableListNode):
ImmutableListNode.printValue():打印当前节点的值。
ImmutableListNode.getNext():返回下一个节点。
输入仅用于在内部初始化链表。您必须在不修改链表的情况下解决此问题。换句话说,您必须仅使用提到的 API 来操作链表。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* // 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) {
ImmutableListNode current = head;
int count = 0;
while (current != null) {
count++;
current = current.getNext();
}
print(0, count - 1, head);
}
public void print(int start, int end, ImmutableListNode head) {
if (start >= end) head.printValue();
else {
int mid = start + (end - start) / 2;
ImmutableListNode midNode = move(start, Math.min(mid + 1, end), head);
print(mid + 1, end, midNode);
print(start, mid, head);
}
}
private ImmutableListNode move(int start, int dest, ImmutableListNode head) {
ImmutableListNode result = head;
while (start++ < dest) {
result = result.getNext();
}
return result;
}
}