{"id":564,"date":"2024-01-03T13:18:21","date_gmt":"2024-01-03T13:18:21","guid":{"rendered":"https:\/\/www.kaashivinfotech.com\/blog\/?p=564"},"modified":"2024-01-03T13:18:21","modified_gmt":"2024-01-03T13:18:21","slug":"reverse-a-linked-list","status":"publish","type":"post","link":"https:\/\/www.kaashivinfotech.com\/blog\/reverse-a-linked-list\/","title":{"rendered":"Reverse a Linked List"},"content":{"rendered":"<h2><strong>Reverse a Linked List<\/strong><\/h2>\n<h2><strong>Problem Statement<\/strong><\/h2>\n<p>Given a singly linked list, the task is to reverse the list, meaning that the last node becomes the first node, the second-to-last node becomes the second node, and so on.<\/p>\n<h2><strong>Recursive Approach<\/strong><\/h2>\n<p>The recursive approach to reversing a linked list involves breaking the problem into smaller subproblems. Here are the general steps:<\/p>\n<ul>\n<li>Divide the linked list into two parts: the first node (head) and the rest of the list (the linked list without the first node).<\/li>\n<li>Recursively reverse the rest of the linked list.<\/li>\n<li>After the recursion, change the next of the last node of the reversed rest to point to the first node.<\/li>\n<li>Set the next of the first node to NULL to make it the new tail.<\/li>\n<\/ul>\n<h2><strong>Implementation of Recursive Approach<\/strong><\/h2>\n<h3><strong>C++ Implementation<\/strong><\/h3>\n<p>#include &lt;iostream&gt;<\/p>\n<div class=\"code-embed-wrapper\"> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">class Node {<br\/><br\/>public:<br\/><br\/>int data;<br\/><br\/>Node* next;<br\/><br\/>Node(int data) : data(data), next(nullptr) {}<br\/><br\/>};<br\/><br\/>Node* reverseLinkedList(Node* head) {<br\/><br\/>if (head == nullptr || head-&gt;next == nullptr) {<br\/><br\/>return head;<br\/><br\/>}<br\/><br\/>Node* restReversed = reverseLinkedList(head-&gt;next);<br\/><br\/>head-&gt;next-&gt;next = head;<br\/><br\/>head-&gt;next = nullptr;<br\/><br\/>return restReversed;<br\/><br\/>}<br\/><br\/>void printLinkedList(Node* head) {<br\/><br\/>while (head != nullptr) {<br\/><br\/>std::cout &lt;&lt; head-&gt;data &lt;&lt; &quot; &quot;;<br\/><br\/>head = head-&gt;next;<br\/><br\/>}<br\/><br\/>std::cout &lt;&lt; std::endl;<br\/><br\/>}<br\/><br\/>int main() {<br\/><br\/>Node* head = new Node(1);<br\/><br\/>head-&gt;next = new Node(2);<br\/><br\/>head-&gt;next-&gt;next = new Node(3);<br\/><br\/>head-&gt;next-&gt;next-&gt;next = new Node(4);<br\/><br\/>std::cout &lt;&lt; &quot;Original Linked List: &quot;;<br\/><br\/>printLinkedList(head);<br\/><br\/>head = reverseLinkedList(head);<br\/><br\/>std::cout &lt;&lt; &quot;Reversed Linked List: &quot;;<br\/><br\/>printLinkedList(head);<br\/><br\/>return 0;<br\/><br\/>}<\/code><\/pre> <div class=\"code-embed-infos\"> <\/div> <\/div>\n<h3><strong>Java Implementation<\/strong><\/h3>\n<div class=\"code-embed-wrapper\"> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">class Node {<br\/><br\/>int data;<br\/><br\/>Node next;<br\/><br\/>Node(int data) {<br\/><br\/>this.data = data;<br\/><br\/>this.next = null;<br\/><br\/>}<br\/><br\/>}<br\/><br\/>public class ReverseLinkedList {<br\/><br\/>public static Node reverseLinkedList(Node head) {<br\/><br\/>if (head == null || head.next == null) {<br\/><br\/>return head;<br\/><br\/>}<br\/><br\/>Node restReversed = reverseLinkedList(head.next);<br\/><br\/>head.next.next = head;<br\/><br\/>head.next = null;<br\/><br\/>return restReversed;<br\/><br\/>}<br\/><br\/>public static void printLinkedList(Node head) {<br\/><br\/>while (head != null) {<br\/><br\/>System.out.print(head.data + &quot; &quot;);<br\/><br\/>head = head.next;<br\/><br\/>}<br\/><br\/>System.out.println();<br\/><br\/>}<br\/><br\/>public static void main(String[] args) {<br\/><br\/>Node head = new Node(1);<br\/><br\/>head.next = new Node(2);<br\/><br\/>head.next.next = new Node(3);<br\/><br\/>head.next.next.next = new Node(4);<br\/><br\/>System.out.print(&quot;Original Linked List: &quot;);<br\/><br\/>printLinkedList(head);<br\/><br\/>head = reverseLinkedList(head);<br\/><br\/>System.out.print(&quot;Reversed Linked List: &quot;);<br\/><br\/>printLinkedList(head);<br\/><br\/>}<br\/><br\/>}<\/code><\/pre> <div class=\"code-embed-infos\"> <\/div> <\/div>\n<h3><strong>Python Implementation<\/strong><\/h3>\n<div class=\"code-embed-wrapper\"> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\">class ListNode:<br\/><br\/>def __init__(self, data):<br\/><br\/>self.data = data<br\/><br\/>self.next = None<br\/><br\/>def reverseLinkedList(head):<br\/><br\/>if head is None or head.next is None:<br\/><br\/>return head<br\/><br\/>restReversed = reverseLinkedList(head.next)<br\/><br\/>head.next.next = head<br\/><br\/>head.next = None<br\/><br\/>return restReversed<br\/><br\/>def printLinkedList(head):<br\/><br\/>while head:<br\/><br\/>print(head.data, end=&quot; &quot;)<br\/><br\/>head = head.next<br\/><br\/>print()<br\/><br\/># Helper function to create a linked list from a list<br\/><br\/>def createLinkedList(arr):<br\/><br\/>if not arr:<br\/><br\/>return None<br\/><br\/>head = ListNode(arr[0])<br\/><br\/>current = head<br\/><br\/>for item in arr[1:]:<br\/><br\/>current.next = ListNode(item)<br\/><br\/>current = current.next<br\/><br\/>return head<br\/><br\/># Helper function to print a linked list<br\/><br\/>def printLinkedList(head):<br\/><br\/>while head:<br\/><br\/>print(head.data, end=&quot; &quot;)<br\/><br\/>head = head.next<br\/><br\/>print()<br\/><br\/>if __name__ == &quot;__main__&quot;:<br\/><br\/>arr = [1, 2, 3, 4]<br\/><br\/>head = createLinkedList(arr)<br\/><br\/>print(&quot;Original Linked List:&quot;, end=&quot; &quot;)<br\/><br\/>printLinkedList(head)<br\/><br\/>head = reverseLinkedList(head)<br\/><br\/>print(&quot;Reversed Linked List:&quot;, end=&quot; &quot;)<br\/><br\/>printLinkedList(head)<\/code><\/pre> <div class=\"code-embed-infos\"> <\/div> <\/div>\n<h2><strong>Iterative Approach<\/strong><\/h2>\n<p>The iterative approach to reversing a linked list involves traversing the list once and modifying the next pointers of each node to reverse the direction of the list.<\/p>\n<h2><strong>Dry Run of the Iterative Approach<\/strong><\/h2>\n<p>Let&#8217;s dry run the iterative approach on a simple example:<\/p>\n<p>Original Linked List: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; null<\/p>\n<ol>\n<li>Initialize three pointers: prev = null, current = head (1st node), and next = null.<\/li>\n<li>Iterate through the linked list.<\/li>\n<\/ol>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>In each iteration, update the next pointer of the current node to point to the previous node (reverse the link).<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li>Update prev to be the current node.<\/li>\n<li>Update current to be the next node (move forward).<\/li>\n<\/ul>\n<ol start=\"3\">\n<li>After the loop, update the head to be prev, which is now pointing to the new first node (4).<\/li>\n<li>The reversed linked list is now: 4 -&gt; 3 -&gt; 2 -&gt; 1 -&gt; null.<\/li>\n<\/ol>\n<h2><strong>Implementation of Iterative Approach<\/strong><\/h2>\n<h3><strong>C++ Implementation<\/strong><\/h3>\n<p>#include &lt;iostream&gt;<\/p>\n<div class=\"code-embed-wrapper\"> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">class Node {<br\/><br\/>public:<br\/><br\/>int data;<br\/><br\/>Node* next;<br\/><br\/>Node(int data) : data(data), next(nullptr) {}<br\/><br\/>};<br\/><br\/>Node* reverseLinkedList(Node* head) {<br\/><br\/>Node* prev = nullptr;<br\/><br\/>Node* current = head;<br\/><br\/>Node* next = nullptr;<br\/><br\/>while (current != nullptr) {<br\/><br\/>next = current-&gt;next;<br\/><br\/>current-&gt;next = prev;<br\/><br\/>prev = current;<br\/><br\/>current = next;<br\/><br\/>}<br\/><br\/>return prev; \/\/ New head of the reversed list<br\/><br\/>}<br\/><br\/>void printLinkedList(Node* head) {<br\/><br\/>while (head != nullptr) {<br\/><br\/>std::cout &lt;&lt; head-&gt;data &lt;&lt; &quot; &quot;;<br\/><br\/>head = head-&gt;next;<br\/><br\/>}<br\/><br\/>std::cout &lt;&lt; std::endl;<br\/><br\/>}<br\/><br\/>int main() {<br\/><br\/>Node* head = new Node(1);<br\/><br\/>head-&gt;next = new Node(2);<br\/><br\/>head-&gt;next-&gt;next = new Node(3);<br\/><br\/>head-&gt;next-&gt;next-&gt;next = new Node(4);<br\/><br\/>std::cout &lt;&lt; &quot;Original Linked List: &quot;;<br\/><br\/>printLinkedList(head);<br\/><br\/>head = reverseLinkedList(head);<br\/><br\/>std::cout &lt;&lt; &quot;Reversed Linked List: &quot;;<br\/><br\/>printLinkedList(head);<br\/><br\/>return 0;<br\/><br\/>}<\/code><\/pre> <div class=\"code-embed-infos\"> <\/div> <\/div>\n<h3><strong>Java Implementation<\/strong><\/h3>\n<div class=\"code-embed-wrapper\"> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">class Node {<br\/><br\/>int data;<br\/><br\/>Node next;<br\/><br\/>Node(int data) {<br\/><br\/>this.data = data;<br\/><br\/>this.next = null;<br\/><br\/>}<br\/><br\/>}<br\/><br\/>public class ReverseLinkedList {<br\/><br\/>public static Node reverseLinkedList(Node head) {<br\/><br\/>Node prev = null;<br\/><br\/>Node current = head;<br\/><br\/>Node next = null;<br\/><br\/>while (current != null) {<br\/><br\/>next = current.next;<br\/><br\/>current.next = prev;<br\/><br\/>prev = current;<br\/><br\/>current = next;<br\/><br\/>}<br\/><br\/>return prev; \/\/ New head of the reversed list<br\/><br\/>}<br\/><br\/>public static void printLinkedList(Node head)<\/code><\/pre> <div class=\"code-embed-infos\"> <\/div> <\/div>\n<h2><strong>FAQs<\/strong><\/h2>\n<h3><strong>1.What is a linked list?<\/strong><\/h3>\n<p>A linked list is a linear data structure consisting of nodes, where each node points to the next node in the sequence. It&#8217;s used to store and manage a collection of elements.<\/p>\n<h3><strong>2.Why would you want to reverse a linked list?<\/strong><\/h3>\n<p>Reversing a linked list can be useful in various scenarios, such as when you need to process elements in a different order, search for elements from the end, or improve the efficiency of certain operations.<\/p>\n<h3><strong>3.What is the difference between reversing a linked list iteratively and recursively?<\/strong><\/h3>\n<p>The iterative approach reverses the linked list by iteratively modifying the next pointers of each node to change the direction of the list. The recursive approach divides the problem into smaller subproblems, recursively reverses the rest of the list, and then combines the results.<\/p>\n<h3><strong>4.Is there a preferred approach (iterative vs. recursive) for reversing a linked list?<\/strong><\/h3>\n<p>The choice between the iterative and recursive approaches often depends on personal preference and the specific requirements of the problem. Both approaches are valid and can achieve the same result.<\/p>\n<h3><strong>5.What is the time complexity of reversing a linked list?<\/strong><\/h3>\n<p>Both the iterative and recursive approaches have a time complexity of O(n), where n is the number of nodes in the linked list. This is because they visit each node once.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Reverse a Linked List Problem Statement Given a singly linked list, the task is to reverse the list, meaning that the last node becomes the first node, the second-to-last node becomes the second node, and so on. Recursive Approach The recursive approach to reversing a linked list involves breaking the problem into smaller subproblems. Here [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2191],"tags":[2493,2483,2498,2484,2487,2489,2491,2482,2497,2492,2490,2494,2496,2488,2485,2495,2486],"class_list":["post-564","post","type-post","status-publish","format-standard","hentry","category-problems","tag-code-to-reverse-a-linked-list","tag-how-to-reverse-a-linked-list","tag-iterative-method-to-reverse-a-linked-list","tag-linked-list","tag-linked-list-reverse","tag-linked-lists","tag-reverse-a-link-list","tag-reverse-a-linked-list","tag-reverse-a-linked-list-iterative-method","tag-reverse-a-linked-list-c","tag-reverse-a-linked-list-in-java","tag-reverse-a-linked-list-python","tag-reverse-a-linked-list-using-recursion","tag-reverse-a-linkedlist","tag-reverse-a-singly-linked-list","tag-reverse-a-singly-linked-list-c-program","tag-reverse-linked-list"],"_links":{"self":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/posts\/564","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/comments?post=564"}],"version-history":[{"count":0,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/posts\/564\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/media?parent=564"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/categories?post=564"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/tags?post=564"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}