@@ -34,6 +34,25 @@ private static Node getKthToLastElement(Node head, int k) {
34
34
return slow ;
35
35
}
36
36
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
+
37
56
public static void main (String [] args ) {
38
57
Node l1 = new Node (1 );
39
58
l1 .next = new Node (6 );
@@ -43,6 +62,8 @@ public static void main(String[] args) {
43
62
l1 .next .next .next .next .next = new Node (7 );
44
63
printList (l1 );
45
64
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 );
46
67
47
68
Node l2 = new Node (1 );
48
69
l2 .next = new Node (6 );
@@ -52,6 +73,8 @@ public static void main(String[] args) {
52
73
l2 .next .next .next .next .next = new Node (7 );
53
74
printList (l2 );
54
75
System .out .println ("k=1: " + getKthToLastElement (l2 , 1 ).val );
76
+ System .out .print ("k=1: " );
77
+ printKthToLastElement (l2 , 1 );
55
78
56
79
Node l3 = new Node (1 );
57
80
l3 .next = new Node (6 );
@@ -61,5 +84,7 @@ public static void main(String[] args) {
61
84
l3 .next .next .next .next .next = new Node (7 );
62
85
printList (l3 );
63
86
System .out .println ("k=6: " + getKthToLastElement (l3 , 6 ).val );
87
+ System .out .print ("k=6: " );
88
+ printKthToLastElement (l3 , 6 );
64
89
}
65
90
}
0 commit comments