-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq2p2.java
More file actions
61 lines (55 loc) · 1.53 KB
/
Copy pathq2p2.java
File metadata and controls
61 lines (55 loc) · 1.53 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
public class q2p2{
public static void main(String[] args){
Node head = new Node(20);
int cnt = 10;
while(cnt > 0){
head.append(cnt--);
}
Node buf = head;
while(buf != null){
System.out.println(buf.value);
buf = buf.next;
}
head.kth(3);
System.out.println("total k time >>"+ head.kthRecursion(head, 3));
}
}
class Node{
public Node next = null;
public int value;
public Node(int value){
this.value = value;
}
public void append(int value){
Node end = new Node(value);
end.value = value;
Node previous = this;
while(previous.next != null){
previous = previous.next;
}
previous.next = end;
}
public void kth(int k){
Node current = this;
while(current != null){
if(k<=0)
System.out.println("element >> "+current.value);
current = current.next;
k--;
}
}
// T: O(n)
// S: O(1)
// A: if using brute force, T:(2n), first n is using for find the length of
// list.
// The bad thing is, we can not use this method to return value.
// Another better way is using k-width window, two pointers.
public int kthRecursion(Node head, int k){
if(head == null)
return 0;
int index = kthRecursion(head.next, k)+1;
if(index == k)
System.out.println(k+"th to last node is"+head.value);
return index;
}
}