Skip to content

Commit b359683

Browse files
committed
Return kth element
1 parent 78136ed commit b359683

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package crackingTheCodingInterview.chap2;
2+
3+
import me.premaseem.myLib.MyDLLNode;
4+
import org.junit.Test;
5+
6+
public class ReturnKToLast {
7+
8+
// Test Driven Development by Aseem Jain
9+
@Test
10+
public void test() {
11+
12+
int[] in = {2, 4, 4, 5, 9, 6, 8, 2};
13+
MyDLLNode head = new MyDLLNode(in);
14+
15+
// get 3rd from last
16+
assert solution1(head,2).data == 8;
17+
assert solution2(head,2).data == 8;
18+
19+
}
20+
21+
// Basic solution
22+
private MyDLLNode solution1(MyDLLNode head, int k) {
23+
24+
// count total number in one loop.
25+
// iterate for last - k to return element
26+
MyDLLNode c = head;
27+
int len =0;
28+
while(c != null){
29+
len++;
30+
c = c.next;
31+
}
32+
33+
c = head;
34+
for (int i = 1; i <= len-k ; i++, c = c.next) {
35+
36+
}
37+
return c;
38+
}
39+
40+
private MyDLLNode solution2(MyDLLNode head, int k) {
41+
42+
// count total number in one loop.
43+
// iterate for last - k to return element
44+
MyDLLNode c = head;
45+
while(c.next != null){
46+
c = c.next;
47+
}
48+
49+
MyDLLNode last = c;
50+
51+
for (int i = 1; i < k ; i++, last = last.prev) {
52+
53+
}
54+
return last;
55+
}
56+
}

0 commit comments

Comments
 (0)