From 4aabf9be2a2378a6787927e8927b4a0368e4743a Mon Sep 17 00:00:00 2001 From: Gaurav Jaiswal Date: Sat, 8 Oct 2022 15:01:34 +0530 Subject: [PATCH] Fix an error in insert method of LinkedList and Add new reverse method in linkedList --- Data Structures and Algorithms/linked_list.py | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/Data Structures and Algorithms/linked_list.py b/Data Structures and Algorithms/linked_list.py index eff2864e..4b5c5758 100644 --- a/Data Structures and Algorithms/linked_list.py +++ b/Data Structures and Algorithms/linked_list.py @@ -77,7 +77,7 @@ def insert(self, data, index): current = self.head while position > 1: - current = node.next_node + current = current.next_node position -= 1 prev_node = current @@ -139,3 +139,21 @@ def __repr__(self): current = current.next_node return "->".join(nodes) + + def reverse(self): + """ + reverses the complete linked list + returns the linked list + the time complexity of it is 0(n) time. + """ + first = self.head + second = self.head.next_node + + while(second != None): + store_rest_list = second.next_node + second.next_node = first + first = second + second = store_rest_list + self.head.next_node = None + self.head = first + return self