From d14587d925df5c54c1cbde35bac0ba830eb9f82e Mon Sep 17 00:00:00 2001 From: urvesh254 Date: Sat, 16 Oct 2021 01:30:50 +0530 Subject: [PATCH] Algorithm for reversing the linkedlist using efficient manner in Python. --- ReverseLinkedList.py | 57 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 ReverseLinkedList.py diff --git a/ReverseLinkedList.py b/ReverseLinkedList.py new file mode 100644 index 0000000..627f512 --- /dev/null +++ b/ReverseLinkedList.py @@ -0,0 +1,57 @@ +""" + Author: Urveshkumar Patel + GitHub: https://github.com/urvesh254 +""" + + +class Node: + """It is a representation of the LinkedList node.""" + + def __init__(self, data, next=None) -> None: + self.data = data + self.next = next + + +def reverseLL(head) -> Node: + """ + Efficient method for reversing the LinkedList. + + Time Complexity: O(n) + Space Complexity: O(1) + + @param head Start pointer of the LinkedList. + @return Updated head after reversing the LinkedList. + """ + + pre, curr, next = None, head, None + while curr: + pre = curr.next + curr.next = next + next = curr + + curr = pre + + return next + + +""" Uncomment below code for Testing """ + +""" +def displayLL(head): + q = head + while q: + print(q.data, end="->") + q = q.next + print() + + +head = Node("1") +head.next = Node("2") +head.next.next = Node("3") +head.next.next.next = Node("4") +head.next.next.next.next = Node("5") +head.next.next.next.next.next = Node("6") + +displayLL(head) +displayLL(reverseLL(head)) +"""