{"id":27294,"date":"2018-01-20T20:47:14","date_gmt":"2018-01-20T15:17:14","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27294"},"modified":"2018-01-20T20:47:14","modified_gmt":"2018-01-20T15:17:14","slug":"python-algorithm-write-function-reverse-linked-list","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-algorithm-write-function-reverse-linked-list\/","title":{"rendered":"Python 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>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program to reverse a linked list <br\/># Time Complexity : O(n)<br\/># Space Complexity : O(1)<br\/> <br\/># Node class <br\/>class Node:<br\/> <br\/>    # Constructor to initialize the node object<br\/>    def __init__(self, data):<br\/>        self.data = data<br\/>        self.next = None<br\/> <br\/>class LinkedList:<br\/> <br\/>    # Function to initialize head<br\/>    def __init__(self):<br\/>        self.head = None<br\/> <br\/>    # Function to reverse the linked list<br\/>    def reverse(self):<br\/>        prev = None<br\/>        current = self.head<br\/>        while(current is not None):<br\/>            next = current.next<br\/>            current.next = prev<br\/>            prev = current<br\/>            current = next<br\/>        self.head = prev<br\/>         <br\/>    # Function to insert a new node at the beginning<br\/>    def push(self, new_data):<br\/>        new_node = Node(new_data)<br\/>        new_node.next = self.head<br\/>        self.head = new_node<br\/> <br\/>    # Utility function to print the linked LinkedList<br\/>    def printList(self):<br\/>        temp = self.head<br\/>        while(temp):<br\/>            print temp.data,<br\/>            temp = temp.next<br\/> <br\/> <br\/># Driver program to test above functions<br\/>llist = LinkedList()<br\/>llist.push(20)<br\/>llist.push(4)<br\/>llist.push(15)<br\/>llist.push(85)<br\/> <br\/>print &quot;Given Linked List&quot;<br\/>llist.printList()<br\/>llist.reverse()<br\/>print &quot;\\nReversed Linked List&quot;<br\/>llist.printList()<br\/> <br\/># This code is contributed by Nikhil Kumar Singh(nickzuck_007)<\/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>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Simple and tail recursive Python program to <br\/># reverse a linked list<br\/> <br\/># Node class <br\/>class Node:<br\/> <br\/>    # Constructor to initialize the node object<br\/>    def __init__(self, data):<br\/>        self.data = data<br\/>        self.next = None<br\/> <br\/>class LinkedList:<br\/> <br\/>    # Function to initialize head<br\/>    def __init__(self):<br\/>        self.head = None<br\/> <br\/> <br\/>    def reverseUtil(self, curr, prev):<br\/>         <br\/>        # If last node mark it head<br\/>        if curr.next is None :<br\/>            self.head = curr <br\/>             <br\/>            # Update next to prev node<br\/>            curr.next = prev<br\/>            return<br\/>         <br\/>        # Save curr.next node for recursive call<br\/>        next = curr.next<br\/> <br\/>        # And update next <br\/>        curr.next = prev<br\/>     <br\/>        self.reverseUtil(next, curr) <br\/> <br\/> <br\/>    # This function mainly calls reverseUtil()<br\/>    # with previous as None<br\/>    def reverse(self):<br\/>        if self.head is None:<br\/>            return<br\/>        self.reverseUtil(self.head, None)<br\/> <br\/> <br\/>    # Function to insert a new node at the beginning<br\/>    def push(self, new_data):<br\/>        new_node = Node(new_data)<br\/>        new_node.next = self.head<br\/>        self.head = new_node<br\/> <br\/>    # Utility function to print the linked LinkedList<br\/>    def printList(self):<br\/>        temp = self.head<br\/>        while(temp):<br\/>            print temp.data,<br\/>            temp = temp.next<br\/> <br\/> <br\/># Driver program<br\/>llist = LinkedList()<br\/>llist.push(8)<br\/>llist.push(7)<br\/>llist.push(6)<br\/>llist.push(5)<br\/>llist.push(4)<br\/>llist.push(3)<br\/>llist.push(2)<br\/>llist.push(1)<br\/> <br\/>print &quot;Given linked list&quot;<br\/>llist.printList()<br\/> <br\/>llist.reverse()<br\/> <br\/>print &quot;\\nReverse linked list&quot;<br\/>llist.printList()<br\/> <br\/># This code is contributed by Nikhil Kumar Singh(nickzuck_007)<\/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>Python 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":[79476,4148,79478],"tags":[80299,81347,81346,81349,80298,80296,81345,80300,81342,81348,80297,81344,81343],"class_list":["post-27294","post","type-post","status-publish","format-standard","hentry","category-linked-list","category-python","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\/27294","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=27294"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27294\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27294"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27294"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27294"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}