{"id":27031,"date":"2018-01-02T20:58:58","date_gmt":"2018-01-02T15:28:58","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27031"},"modified":"2018-01-02T20:58:58","modified_gmt":"2018-01-02T15:28:58","slug":"java-algorithm-find-nth-node-end-linked-list","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-algorithm-find-nth-node-end-linked-list\/","title":{"rendered":"Java Algorithm &#8211; Find n\u2019th node from the end of a Linked List"},"content":{"rendered":"<p>Given a Linked List and a number n, write a function that returns the value at the n\u2019th node from end of the Linked List.<\/p>\n<p><strong>Method 1 (Use length of linked list)<\/strong><br \/>\n1) Calculate the length of Linked List. Let the length be len.<br \/>\n2) Print the (len \u2013 n + 1)th node from the begining of the Linked List.<\/p>\n<p><strong>Java Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Simple Java program to find n&#039;th node from end of linked list<br\/>class LinkedList<br\/>{<br\/>    Node head; \/\/ head of the list<br\/> <br\/>    \/* Linked List node *\/<br\/>    class Node<br\/>    {<br\/>        int data;<br\/>        Node next;<br\/>        Node(int d)<br\/>        {<br\/>            data = d;<br\/>            next = null;<br\/>        }<br\/>    }<br\/> <br\/>    \/* Function to get the nth node from the last of a<br\/>       linked list *\/<br\/>    void printNthFromLast(int n)<br\/>    {<br\/>        int len = 0;<br\/>        Node temp = head;<br\/> <br\/>        \/\/ 1) count the number of nodes in Linked List<br\/>        while (temp != null)<br\/>        {<br\/>            temp = temp.next;<br\/>            len++;<br\/>        }<br\/> <br\/>        \/\/ check if value of n is not more than length of<br\/>        \/\/ the linked list<br\/>        if (len &lt; n)<br\/>            return;<br\/> <br\/>        temp = head;<br\/> <br\/>        \/\/ 2) get the (n-len+1)th node from the begining<br\/>        for (int i = 1; i &lt; len-n+1; i++)<br\/>            temp = temp.next;<br\/> <br\/>        System.out.println(temp.data);<br\/>    }<br\/> <br\/>    \/* Inserts a new Node at front of the list. *\/<br\/>    public void push(int new_data)<br\/>    {<br\/>        \/* 1 &amp; 2: Allocate the Node &amp;<br\/>                  Put in the data*\/<br\/>        Node new_node = new Node(new_data);<br\/> <br\/>        \/* 3. Make next of new Node as head *\/<br\/>        new_node.next = head;<br\/> <br\/>        \/* 4. Move the head to point to new Node *\/<br\/>        head = new_node;<br\/>    }<br\/> <br\/>    \/*Drier program to test above methods *\/<br\/>    public static void main(String [] args)<br\/>    {<br\/>        LinkedList llist = new LinkedList();<br\/>        llist.push(20);<br\/>        llist.push(4);<br\/>        llist.push(15);<br\/>        llist.push(35);<br\/> <br\/>        llist.printNthFromLast(4);<br\/>    }<br\/>}\/\/ This code is contributed by Rajat Mishra<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>35<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p>Following is a recursive C code for the same method. Thanks to Anuj Bansal for providing following code.<\/p>\n<p><strong>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">void printNthFromLast(struct node* head, int n) <br\/>{<br\/>    static int i = 0;<br\/>    if (head == NULL)<br\/>       return;<br\/>    printNthFromLast(head-&gt;next, n);<br\/>    if (++i == n)<br\/>       printf(&quot;%d&quot;, head-&gt;data);<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Time Complexity:<\/strong> O(n) where n is the length of linked list.<br \/>\n<strong>Method 2 (Use two pointers) <\/strong><br \/>\nMaintain two pointers \u2013 reference pointer and main pointer. Initialize both reference and main pointers to head. First move reference pointer to n nodes from head. Now move both pointers one by one until reference pointer reaches end. Now main pointer will point to nth node from the end. Return main pointer.<\/p>\n<p><strong>Java Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to find n&#039;th node from end using slow and<br\/>\/\/ fast pointers<br\/>class LinkedList<br\/>{<br\/>    Node head; \/\/ head of the list<br\/> <br\/>    \/* Linked List node *\/<br\/>    class Node<br\/>    {<br\/>        int data;<br\/>        Node next;<br\/>        Node(int d)<br\/>        {<br\/>            data = d;<br\/>            next = null;<br\/>        }<br\/>    }<br\/> <br\/>    \/* Function to get the nth node from end of list *\/<br\/>    void printNthFromLast(int n)<br\/>    {<br\/>        Node main_ptr = head;<br\/>        Node ref_ptr = head;<br\/> <br\/>        int count = 0;<br\/>        if (head != null)<br\/>        {<br\/>            while (count &lt; n)<br\/>            {<br\/>                if (ref_ptr == null)<br\/>                {<br\/>                    System.out.println(n+&quot; is greater than the no &quot;+<br\/>                                      &quot; of nodes in the list&quot;);<br\/>                    return;<br\/>                }<br\/>                ref_ptr = ref_ptr.next;<br\/>                count++;<br\/>            }<br\/>            while (ref_ptr != null)<br\/>            {<br\/>                main_ptr = main_ptr.next;<br\/>                ref_ptr = ref_ptr.next;<br\/>            }<br\/>            System.out.println(&quot;Node no. &quot;+n+&quot; from last is &quot;+<br\/>                               main_ptr.data);<br\/>        }<br\/>    }<br\/> <br\/>    \/* Inserts a new Node at front of the list. *\/<br\/>    public void push(int new_data)<br\/>    {<br\/>        \/* 1 &amp; 2: Allocate the Node &amp;<br\/>                  Put in the data*\/<br\/>        Node new_node = new Node(new_data);<br\/> <br\/>        \/* 3. Make next of new Node as head *\/<br\/>        new_node.next = head;<br\/> <br\/>        \/* 4. Move the head to point to new Node *\/<br\/>        head = new_node;<br\/>    }<br\/> <br\/>    \/*Drier program to test above methods *\/<br\/>    public static void main(String [] args)<br\/>    {<br\/>        LinkedList llist = new LinkedList();<br\/>        llist.push(20);<br\/>        llist.push(4);<br\/>        llist.push(15);<br\/>        llist.push(35);<br\/> <br\/>        llist.printNthFromLast(4);<br\/>    }<br\/>} \/\/ This code is contributed by Rajat Mishra<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Node no. 4 from last is 35<\/pre>\n<p><strong>Time Complexity:<\/strong> O(n) where n is the length of linked list<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Algorithm &#8211; Find n\u2019th node from the end of a Linked List &#8211; Linked List &#8211; Given a Linked List and a number n, write a function that returns the value<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[79476,79478],"tags":[80490,80665,80661,80492,80659,80489,80493,80666,80660,80491],"class_list":["post-27031","post","type-post","status-publish","format-standard","hentry","category-linked-list","category-singly-linked-list","tag-delete-nth-element-in-linked-list","tag-delete-nth-element-in-linked-list-java","tag-delete-nth-node-from-end-of-linked-list","tag-find-middle-element-in-linked-list-java","tag-find-nth-element-in-linked-list","tag-find-nth-element-in-linked-list-c","tag-find-nth-to-last-element-in-a-linked-list-recursion","tag-linked-list-in-cc-delete-a-node-at-nth-position","tag-remove-nth-node-from-end-of-list-c","tag-search-a-node-in-linked-list-in-c"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27031","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27031"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27031\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27031"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27031"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27031"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}