{"id":27029,"date":"2018-01-02T20:59:35","date_gmt":"2018-01-02T15:29:35","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27029"},"modified":"2018-01-02T20:59:35","modified_gmt":"2018-01-02T15:29:35","slug":"c-algorithm-find-nth-node-end-linked-list","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-algorithm-find-nth-node-end-linked-list\/","title":{"rendered":"C 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>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\">\/\/ Simple C program to find n&#039;th node from end<br\/>#include&lt;stdio.h&gt;<br\/>#include&lt;stdlib.h&gt;<br\/> <br\/>\/* Link list node *\/<br\/>struct node<br\/>{<br\/>  int data;<br\/>  struct node* next;<br\/>};<br\/> <br\/>\/* Function to get the nth node from the last of a linked list*\/<br\/>void printNthFromLast(struct node* head, int n)<br\/>{<br\/>    int len = 0, i;<br\/>    struct node *temp = head;<br\/> <br\/>    \/\/ 1) count the number of nodes in Linked List<br\/>    while (temp != NULL)<br\/>    {<br\/>        temp = temp-&gt;next;<br\/>        len++;<br\/>    }<br\/> <br\/>    \/\/ check if value of n is not more than length of 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 (i = 1; i &lt; len-n+1; i++)<br\/>       temp = temp-&gt;next;<br\/> <br\/>    printf (&quot;%d&quot;, temp-&gt;data);<br\/> <br\/>    return;<br\/>}<br\/> <br\/>void push(struct node** head_ref, int new_data)<br\/>{<br\/>  \/* allocate node *\/<br\/>  struct node* new_node =<br\/>          (struct node*) malloc(sizeof(struct node));<br\/> <br\/>  \/* put in the data  *\/<br\/>  new_node-&gt;data  = new_data;<br\/> <br\/>  \/* link the old list off the new node *\/<br\/>  new_node-&gt;next = (*head_ref);<br\/> <br\/>  \/* move the head to point to the new node *\/<br\/>  (*head_ref)    = new_node;<br\/>}<br\/> <br\/>\/* Drier program to test above function*\/<br\/>int main()<br\/>{<br\/>  \/* Start with the empty list *\/<br\/>  struct node* head = NULL;<br\/> <br\/>  \/\/ create linked 35-&gt;15-&gt;4-&gt;20<br\/>  push(&amp;head, 20);<br\/>  push(&amp;head, 4);<br\/>  push(&amp;head, 15);<br\/>  push(&amp;head, 35);<br\/> <br\/>  printNthFromLast(head, 5);<br\/>  return 0; <br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>35<\/pre>\n<p>Following is a recursive C code for the same method. Thanks to Anuj Bansal for providing following code.<\/p>\n[ad type=&#8221;banner&#8221;]\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>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\">\/\/ C program to find n&#039;th node from end using slow and<br\/>\/\/ fast pointers<br\/>#include&lt;stdio.h&gt;<br\/>#include&lt;stdlib.h&gt;<br\/> <br\/>\/* Link list node *\/<br\/>struct node<br\/>{<br\/>  int data;<br\/>  struct node* next;<br\/>};<br\/> <br\/>\/* Function to get the nth node from the last of a linked list*\/<br\/>void printNthFromLast(struct node *head, int n)<br\/>{<br\/>  struct node *main_ptr = head;<br\/>  struct 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\/>           printf(&quot;%d is greater than the no. of &quot;<br\/>                    &quot;nodes in list&quot;, n);<br\/>           return;<br\/>        }<br\/>        ref_ptr = ref_ptr-&gt;next;<br\/>        count++;<br\/>     } \/* End of while*\/<br\/> <br\/>     while(ref_ptr != NULL)<br\/>     {<br\/>        main_ptr = main_ptr-&gt;next;<br\/>        ref_ptr  = ref_ptr-&gt;next;<br\/>     }<br\/>     printf(&quot;Node no. %d from last is %d &quot;, <br\/>              n, main_ptr-&gt;data);<br\/>  }<br\/>}<br\/> <br\/>void push(struct node** head_ref, int new_data)<br\/>{<br\/>  \/* allocate node *\/<br\/>  struct node* new_node =<br\/>          (struct node*) malloc(sizeof(struct node));<br\/> <br\/>  \/* put in the data  *\/<br\/>  new_node-&gt;data  = new_data;<br\/> <br\/>  \/* link the old list off the new node *\/<br\/>  new_node-&gt;next = (*head_ref);    <br\/> <br\/>  \/* move the head to point to the new node *\/<br\/>  (*head_ref)    = new_node;<br\/>}<br\/> <br\/>\/* Drier program to test above function*\/<br\/>int main()<br\/>{<br\/>  \/* Start with the empty list *\/<br\/>  struct node* head = NULL;<br\/>  push(&amp;head, 20);<br\/>  push(&amp;head, 4);<br\/>  push(&amp;head, 15);<br\/>  push(&amp;head, 35);<br\/> <br\/>  printNthFromLast(head, 4);<br\/>}<\/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>C 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":[69866,1,79476,79478],"tags":[80492,80659,80489,80493,80666,80660,80491],"class_list":["post-27029","post","type-post","status-publish","format-standard","hentry","category-c-programming","category-coding","category-linked-list","category-singly-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\/27029","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=27029"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27029\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27029"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27029"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27029"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}