-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathReturnKthToLast.java
More file actions
78 lines (71 loc) · 1.61 KB
/
ReturnKthToLast.java
File metadata and controls
78 lines (71 loc) · 1.61 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package chapter02LinkedList;
/**
* Problem: Implement an algorithm to find the kth to last element of a singly
* linked list. 1 -> 2 -> 3 3th to last node is 1
*
*/
class Index {
public int value = 0;
}
public class ReturnKthToLast {
/**
* method 1: recursion; Space O(N)
*/
public int printKthToLast(ListNode head, int k) {
if (head == null) {
return 0;
}
int index = printKthToLast(head.next, k) + 1;
if (index == k) {
System.out.println(k + "th to last node is " + head.val);
}
return index;
}
/**
* method 2: Wrapper class, recursion; Space O(N)
*/
public ListNode kthToLast(ListNode head, int k) {
Index idx = new Index();
return helper(head, k, idx);
}
private ListNode helper(ListNode head, int k, Index idx) {
if (head == null) {
return null;
}
ListNode node = helper(head.next, k, idx);
idx.value = idx.value + 1;
if (idx.value == k) {
return head;
}
return node;
}
/**
* mehtod 3: iteration Time: O(N), Space O(1)
*/
public ListNode kthToLast3(ListNode node, int k) {
ListNode left = node;
ListNode right = node;
for (int i = 0; i < k; i++) {
if (right == null) {
return null;
}
System.out.println("==" + right.val);
right = right.next;
}
while (right != null) {
right = right.next;
left = left.next;
}
return left;
}
public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
n1.next = n2;
n2.next = n3;
ReturnKthToLast rmd = new ReturnKthToLast();
// rmd.printKthToLast(n1, 3);
System.out.println(rmd.kthToLast3(n1, 1).val);
}
}