Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c0cf56c

Browse files
committed
KthToLastElement: recursive method added
1 parent 65b4dcd commit c0cf56c

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/main/java/com/ctci/linkedlists/KthToLastElement.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,25 @@ private static Node getKthToLastElement(Node head, int k) {
3434
return slow;
3535
}
3636

37+
/**
38+
* This approach is recursive and it just prints the kth to last node instead
39+
* of returning the node.
40+
*
41+
* @param head starting node of the linklist
42+
* @param k kth to last node to print
43+
* @return the index of the kth to last node
44+
*/
45+
private static int printKthToLastElement(Node head, int k) {
46+
if (head == null) {
47+
return 0;
48+
}
49+
int index = printKthToLastElement(head.next, k) + 1;
50+
if (index == k) {
51+
System.out.println(head.val);
52+
}
53+
return index;
54+
}
55+
3756
public static void main(String[] args) {
3857
Node l1 = new Node(1);
3958
l1.next = new Node(6);
@@ -43,6 +62,8 @@ public static void main(String[] args) {
4362
l1.next.next.next.next.next = new Node(7);
4463
printList(l1);
4564
System.out.println("k=2: " + getKthToLastElement(l1, 2).val); // NPE check is omitted intentionally to keep it simple
65+
System.out.print("k=2: ");
66+
printKthToLastElement(l1, 2);
4667

4768
Node l2 = new Node(1);
4869
l2.next = new Node(6);
@@ -52,6 +73,8 @@ public static void main(String[] args) {
5273
l2.next.next.next.next.next = new Node(7);
5374
printList(l2);
5475
System.out.println("k=1: " + getKthToLastElement(l2, 1).val);
76+
System.out.print("k=1: ");
77+
printKthToLastElement(l2, 1);
5578

5679
Node l3 = new Node(1);
5780
l3.next = new Node(6);
@@ -61,5 +84,7 @@ public static void main(String[] args) {
6184
l3.next.next.next.next.next = new Node(7);
6285
printList(l3);
6386
System.out.println("k=6: " + getKthToLastElement(l3, 6).val);
87+
System.out.print("k=6: ");
88+
printKthToLastElement(l3, 6);
6489
}
6590
}

src/main/java/com/ctci/linkedlists/RemoveDuplicates.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,5 +72,19 @@ public static void main(String[] args) {
7272
removeDuplicatesFromUnsortedList(l3);
7373
System.out.print("Without dups: ");
7474
printList(l3);
75+
76+
Node l4 = new Node(1);
77+
System.out.print("\nWith dups: ");
78+
printList(l4);
79+
removeDuplicatesFromUnsortedList(l4);
80+
System.out.print("Without dups: ");
81+
printList(l4);
82+
83+
Node l5 = null;
84+
System.out.print("\nWith dups: ");
85+
printList(l5);
86+
removeDuplicatesFromUnsortedList(l5);
87+
System.out.print("Without dups: ");
88+
printList(l5);
7589
}
7690
}

0 commit comments

Comments
 (0)