Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2ce41b3

Browse files
Return kth element
1 parent b359683 commit 2ce41b3

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

‎src/crackingTheCodingInterview/chap2/ReturnKToLast.java

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
import me.premaseem.myLib.MyDLLNode;
44
import org.junit.Test;
55

6+
/**
7+
### Return Kth to Last:
8+
Implement an algorithm to find the kth to last element of a singly linked list.
9+
10+
*/
611
public class ReturnKToLast {
712

813
// Test Driven Development by Aseem Jain
@@ -24,33 +29,31 @@ private MyDLLNode solution1(MyDLLNode head, int k) {
2429
// count total number in one loop.
2530
// iterate for last - k to return element
2631
MyDLLNode c = head;
27-
int len =0;
28-
while(c != null){
32+
int len =0;
33+
while(c != null){
2934
len++;
3035
c = c.next;
3136
}
3237

33-
c = head;
34-
for (int i = 1; i <= len-k ; i++, c = c.next) {
38+
System.out.println("the total leng is " + len);
3539

40+
c = head;
41+
for (int i = 1; i <= len -k; i++) {
42+
c = c.next;
3643
}
3744
return c;
3845
}
3946

4047
private MyDLLNode solution2(MyDLLNode head, int k) {
41-
42-
// count total number in one loop.
43-
// iterate for last - k to return element
4448
MyDLLNode c = head;
45-
while(c.next != null){
49+
while(c.next != null){
4650
c = c.next;
4751
}
4852

49-
MyDLLNode last = c;
50-
51-
for (int i = 1; i < k ; i++, last = last.prev) {
52-
53+
for (int i = 1; i < k ; i++) {
54+
c = c.prev;
5355
}
54-
return last;
56+
57+
return c;
5558
}
5659
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /