File tree Expand file tree Collapse file tree 2 files changed +24
-46
lines changed
DataStructures/LinkedList/com/java4u/ds/linkedlist/nthNode Expand file tree Collapse file tree 2 files changed +24
-46
lines changed Original file line number Diff line number Diff line change 33import com .java4u .ds .linkedlist .Node ;
44
55public class NthNodeFromLast {
6- public Node NthNodeFromEnd (Node head , int n ) {
7- Node temp = head ;
8- Node pthNode = null ;
9- for (int i = 0 ; i < n ; i ++) {
10- if (temp != null ) {
11- temp = temp .getNext ();
12- }
6+ public int NthNodeFromEnd (Node head , int nodeFromLast ) {
7+
8+ if (nodeFromLast <= 0 || head == null ) {
9+ return -1 ;
1310 }
14- while (temp != null ) {
15- if (pthNode != null ) {
16- pthNode = head ;
17- } else {
18- pthNode = pthNode .getNext ();
11+
12+ Node ptrA = head , ptrB = head ;
13+
14+ for (int i = 0 ; i < nodeFromLast ; i ++) {
15+
16+ if (ptrB == null ) {
17+ return -1 ;
1918 }
20- temp = temp .getNext ();
19+ ptrB = ptrB .getNext ();
2120 }
22-
23- if (pthNode != null ) {
24- return pthNode ;
25- } else {
26- return null ;
21+ while (ptrB != null ) {
22+ ptrB = ptrB .getNext ();
23+ ptrA = ptrA .getNext ();
2724 }
2825
26+ return ptrA .getData ();
27+
2928 }
3029
3130 public static void main (String [] args ) {
@@ -42,10 +41,7 @@ public static void main(String[] args) {
4241 n2 .setNext (n3 );
4342 n3 .setNext (n4 );
4443 n4 .setNext (n5 );
45- Node node = list .NthNodeFromEnd (head , 2 );
46- if (node != null ) {
47- System .out .println (node .getData ());
48- }
44+ System .out .println (list .NthNodeFromEnd (head , 2 ));
4945
5046 }
5147}
Original file line number Diff line number Diff line change @@ -7,33 +7,15 @@ public class NthNodeFromLastUsingRecursion {
77 int count = 0 ;
88
99 public int nthNodeFromEnd (Node head , int nodeFromLast ) {
10-
11- if (nodeFromLast <= 0 || head == null ) {
10+ if (head == null ) {
1211 return -1 ;
1312 }
14-
15- Node ptrA = head , ptrB = head ;
16-
17- // Moving ptrB N nodes from start keeping ptrA at head node.
18- for (int i = 0 ; i < nodeFromLast ; i ++) {
19-
20- // If ptrB reaches NULL, then return -1 as indication that given Nth value is
21- // incorrect and list doesn't contain N elements.
22- if (ptrB == null ) {
23- return -1 ;
24- }
25- ptrB = ptrB .getNext ();
26- }
27-
28- // Now incrementing ptrA and ptrB one node at a time until ptrB encounters NULL,
29- // when it encounters NULL then ptrA will be at Nth position from end of list.
30- while (ptrB != null ) {
31- ptrB = ptrB .getNext ();
32- ptrA = ptrA .getNext ();
13+ int data = nthNodeFromEnd (head .getNext (), nodeFromLast );
14+ count ++;
15+ if (count == nodeFromLast ) {
16+ return head .getData ();
3317 }
34-
35- return ptrA .getData ();
36-
18+ return data ;
3719 }
3820
3921 public static void main (String [] args ) {
You can’t perform that action at this time.
0 commit comments