{"id":27293,"date":"2018-01-20T20:46:48","date_gmt":"2018-01-20T15:16:48","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27293"},"modified":"2018-01-20T20:46:48","modified_gmt":"2018-01-20T15:16:48","slug":"java-algorithm-write-function-reverse-linked-list","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-algorithm-write-function-reverse-linked-list\/","title":{"rendered":"Java 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>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\">#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>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 for reversing the Linked list<br\/> <br\/>class LinkedList {<br\/> <br\/>    static Node head;<br\/> <br\/>    static class Node {<br\/> <br\/>        int data;<br\/>        Node next;<br\/> <br\/>        Node(int d) {<br\/>            data = d;<br\/>            next = null;<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ A simple and tail recursive function to reverse<br\/>    \/\/ a linked list.  prev is passed as NULL initially.<br\/>    Node reverseUtil(Node curr, Node prev) {<br\/> <br\/>        \/* If last node mark it head*\/<br\/>        if (curr.next == null) {<br\/>            head = curr;<br\/> <br\/>            \/* Update next to prev node *\/<br\/>            curr.next = prev;<br\/>            return null;<br\/>        }<br\/> <br\/>        \/* Save curr-&gt;next node for recursive call *\/<br\/>        Node next1 = curr.next;<br\/> <br\/>        \/* and update next ..*\/<br\/>        curr.next = prev;<br\/> <br\/>        reverseUtil(next1, curr);<br\/>        return head;<br\/>    }<br\/> <br\/>    \/\/ prints content of double linked list<br\/>    void printList(Node node) {<br\/>        while (node != null) {<br\/>            System.out.print(node.data + &quot; &quot;);<br\/>            node = node.next;<br\/>        }<br\/>    }<br\/> <br\/>    public static void main(String[] args) {<br\/>        LinkedList list = new LinkedList();<br\/>        list.head = new Node(1);<br\/>        list.head.next = new Node(2);<br\/>        list.head.next.next = new Node(3);<br\/>        list.head.next.next.next = new Node(4);<br\/>        list.head.next.next.next.next = new Node(5);<br\/>        list.head.next.next.next.next.next = new Node(6);<br\/>        list.head.next.next.next.next.next.next = new Node(7);<br\/>        list.head.next.next.next.next.next.next.next = new Node(8);<br\/> <br\/>        System.out.println(&quot;Original Linked list &quot;);<br\/>        list.printList(head);<br\/>        Node res = list.reverseUtil(head, null);<br\/>        System.out.println(&quot;&quot;);<br\/>        System.out.println(&quot;&quot;);<br\/>        System.out.println(&quot;Reversed linked list &quot;);<br\/>        list.printList(res);<br\/>    }<br\/>}<br\/> <br\/> <br\/>\/\/ This code has been contributed by Mayank Jaiswal<\/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>Java 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":[1,2139,79476,79478],"tags":[80299,81347,81346,81349,80298,80296,81345,80300,81342,81348,80297,81344,81343],"class_list":["post-27293","post","type-post","status-publish","format-standard","hentry","category-coding","category-java","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\/27293","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=27293"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27293\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27293"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27293"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27293"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}