{"id":27260,"date":"2018-01-20T20:41:50","date_gmt":"2018-01-20T15:11:50","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27260"},"modified":"2018-01-20T20:41:50","modified_gmt":"2018-01-20T15:11:50","slug":"write-function-reverse-linked-list","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/write-function-reverse-linked-list\/","title":{"rendered":"C Algorithm &#8211; Write a function to reverse a linked list"},"content":{"rendered":"<p>Given pointer to the head node of a linked list, the task is to reverse the linked list.<\/p>\n<p><strong>Examples<\/strong>:<\/p>\n<pre>Input : Head of following linked list  \r\n       1-&gt;2-&gt;3-&gt;4-&gt;NULL\r\nOutput : Linked list should be changed to,\r\n       4-&gt;3-&gt;2-&gt;1-&gt;NULL\r\n\r\nInput : Head of following linked list  \r\n       1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL\r\nOutput : Linked list should be changed to,\r\n       5-&gt;4-&gt;3-&gt;2-&gt;1-&gt;NULL\r\n\r\nInput : NULL\r\nOutput : NULL\r\n\r\nInput  : 1-&gt;NULL\r\nOutput : 1-&gt;NULL<\/pre>\n<div id=\"practice\">\n[ad type=&#8221;banner&#8221;]\n<p><strong>Iterative Method<\/strong><br \/>\nIterate trough the linked list. In loop, change next to prev, prev to current and current to next<\/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\">#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 reverse the linked list *\/<br\/>static void reverse(struct node** head_ref)<br\/>{<br\/>    struct node* prev   = NULL;<br\/>    struct node* current = *head_ref;<br\/>    struct node* next;<br\/>    while (current != NULL)<br\/>    {<br\/>        next  = current-&gt;next;  <br\/>        current-&gt;next = prev;   <br\/>        prev = current;<br\/>        current = next;<br\/>    }<br\/>    *head_ref = prev;<br\/>}<br\/> <br\/>\/* Function to push a node *\/<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\/>\/* Function to print linked list *\/<br\/>void printList(struct node *head)<br\/>{<br\/>    struct node *temp = head;<br\/>    while(temp != NULL)<br\/>    {<br\/>        printf(&quot;%d  &quot;, temp-&gt;data);    <br\/>        temp = temp-&gt;next;  <br\/>    }<br\/>}    <br\/> <br\/>\/* Driver program to test above function*\/<br\/>int main()<br\/>{<br\/>    \/* Start with the empty list *\/<br\/>    struct node* head = NULL;<br\/>   <br\/>     push(&amp;head, 20);<br\/>     push(&amp;head, 4);<br\/>     push(&amp;head, 15); <br\/>     push(&amp;head, 85);      <br\/>     <br\/>     printf(&quot;Given linked list\\n&quot;);<br\/>     printList(head);    <br\/>     reverse(&amp;head);                      <br\/>     printf(&quot;\\nReversed Linked list \\n&quot;);<br\/>     printList(head);    <br\/>     getchar();<br\/>}<\/code><\/pre> <\/div>\n<pre>Given linked list\r\n85 15 4 20 \r\nReversed Linked list \r\n20 4 15 85<\/pre>\n<p><strong>Time Complexity:<\/strong> O(n)<br \/>\n<strong>Space Complexity:<\/strong> O(1)<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Recursive Method:<\/strong><\/p>\n<pre>   1) Divide the list in two parts - first node and rest of the linked list.\r\n   2) Call reverse for the rest of the linked list.\r\n   3) Link rest to first.\r\n   4) Fix head pointer<\/pre>\n<\/div>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-27280\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linked-List-Rverse.png\" alt=\"Write a function to reverse a linked list\" width=\"400\" height=\"420\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linked-List-Rverse.png 400w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linked-List-Rverse-286x300.png 286w\" sizes=\"(max-width: 400px) 100vw, 400px\" \/><\/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 recursiveReverse(struct node** head_ref)<br\/>{<br\/>    struct node* first;<br\/>    struct node* rest;<br\/>      <br\/>    \/* empty list *\/<br\/>    if (*head_ref == NULL)<br\/>       return;   <br\/> <br\/>    \/* suppose first = {1, 2, 3}, rest = {2, 3} *\/<br\/>    first = *head_ref;  <br\/>    rest  = first-&gt;next;<br\/> <br\/>    \/* List has only one node *\/<br\/>    if (rest == NULL)<br\/>       return;   <br\/> <br\/>    \/* reverse the rest list and put the first element at the end *\/<br\/>    recursiveReverse(&amp;rest);<br\/>    first-&gt;next-&gt;next  = first;  <br\/>     <br\/>    \/* tricky step -- see the diagram *\/<br\/>    first-&gt;next  = NULL;          <br\/> <br\/>    \/* fix the head pointer *\/<br\/>    *head_ref = rest;              <br\/>}<\/code><\/pre> <\/div>\n<p><strong>Time Complexity:<\/strong> O(n)<br \/>\n<strong>Space Complexity:<\/strong> O(1)<\/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-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ A simple and tail recursive C++ program to reverse<br\/>\/\/ a linked list<br\/>#include&lt;bits\/stdc++.h&gt;<br\/>using namespace std;<br\/> <br\/>struct node<br\/>{<br\/>    int data;<br\/>    struct node *next;<br\/>};<br\/> <br\/>void reverseUtil(node *curr, node *prev, node **head);<br\/> <br\/>\/\/ This function mainly calls reverseUtil()<br\/>\/\/ with prev as NULL<br\/>void reverse(node **head)<br\/>{<br\/>    if (!head)<br\/>        return;<br\/>    reverseUtil(*head, NULL, head);<br\/>}<br\/> <br\/>\/\/ A simple and tail recursive function to reverse<br\/>\/\/ a linked list.  prev is passed as NULL initially.<br\/>void reverseUtil(node *curr, node *prev, node **head)<br\/>{<br\/>    \/* If last node mark it head*\/<br\/>    if (!curr-&gt;next)<br\/>    {<br\/>        *head = curr;<br\/> <br\/>        \/* Update next to prev node *\/<br\/>        curr-&gt;next = prev;<br\/>        return;<br\/>    }<br\/> <br\/>    \/* Save curr-&gt;next node for recursive call *\/<br\/>    node *next = curr-&gt;next;<br\/> <br\/>    \/* and update next ..*\/<br\/>    curr-&gt;next = prev;<br\/> <br\/>    reverseUtil(next, curr, head);<br\/>}<br\/> <br\/>\/\/ A utility function to create a new node<br\/>node *newNode(int key)<br\/>{<br\/>    node *temp = new node;<br\/>    temp-&gt;data = key;<br\/>    temp-&gt;next = NULL;<br\/>    return temp;<br\/>}<br\/> <br\/>\/\/ A utility function to print a linked list<br\/>void printlist(node *head)<br\/>{<br\/>    while(head != NULL)<br\/>    {<br\/>        cout &lt;&lt; head-&gt;data &lt;&lt; &quot; &quot;;<br\/>        head = head-&gt;next;<br\/>    }<br\/>    cout &lt;&lt; endl;<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    node *head1 = newNode(1);<br\/>    head1-&gt;next = newNode(2);<br\/>    head1-&gt;next-&gt;next = newNode(3);<br\/>    head1-&gt;next-&gt;next-&gt;next = newNode(4);<br\/>    head1-&gt;next-&gt;next-&gt;next-&gt;next = newNode(5);<br\/>    head1-&gt;next-&gt;next-&gt;next-&gt;next-&gt;next = newNode(6);<br\/>    head1-&gt;next-&gt;next-&gt;next-&gt;next-&gt;next-&gt;next = newNode(7);<br\/>    head1-&gt;next-&gt;next-&gt;next-&gt;next-&gt;next-&gt;next-&gt;next = newNode(8);<br\/>    cout &lt;&lt; &quot;Given linked list\\n&quot;;<br\/>    printlist(head1);<br\/>    reverse(&amp;head1);<br\/>    cout &lt;&lt; &quot;\\nReversed linked list\\n&quot;;<br\/>    printlist(head1);<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Output:<\/strong><\/p>\n<pre>Given linked list\r\n1 2 3 4 5 6 7 8\r\n\r\nReversed linked list\r\n8 7 6 5 4 3 2 1<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>C Algorithm &#8211; Write a function to reverse a linked list &#8211; Linked List &#8211; Given pointer to the head node of a linked list, the task is to reverse<\/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":[80299,81347,81346,81349,80298,80296,81345,80300,81342,81348,80297,81344,81343],"class_list":["post-27260","post","type-post","status-publish","format-standard","hentry","category-c-programming","category-coding","category-linked-list","category-singly-linked-list","tag-algorithm-to-reverse-a-linked-list-in-data-structure","tag-how-to-reverse-a-linked-list-c","tag-how-to-reverse-a-linked-list-in-c","tag-how-to-reverse-a-linked-list-python","tag-reverse-a-linked-list-algorithm","tag-reverse-a-linked-list-c","tag-reverse-a-linked-list-in-groups-of-size-k","tag-reverse-a-linked-list-recursively-c","tag-reverse-a-linked-list-using-recursion","tag-reverse-doubly-linked-list-java","tag-reverse-linked-list-recursive-java","tag-reversing-a-linked-list-in-c-with-explanation","tag-reversing-a-linked-list-in-java"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27260","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=27260"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27260\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27260"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27260"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27260"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}