From 47756d5629c46ceb8553c45e3d60a284b41df3f1 Mon Sep 17 00:00:00 2001 From: edwinpav Date: Thu, 14 Dec 2023 20:24:21 -0500 Subject: [PATCH] add length and rotate method to linkedlist.py --- easyPythonpi/methods/linkedlist.py | 48 ++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/easyPythonpi/methods/linkedlist.py b/easyPythonpi/methods/linkedlist.py index fd49a7c..a2ef3c3 100644 --- a/easyPythonpi/methods/linkedlist.py +++ b/easyPythonpi/methods/linkedlist.py @@ -40,3 +40,51 @@ def display_nodes(head:'node')->'int': t=t.next print("NULL") +# get length of list +def get_linked_list_length(head:'node')->'int': + + # base case + if head is None: + return 0 + + length, curr = 1, head + # loop through list to accumulate length + while head.next: + head = head.next + length += 1 + + return length + +# given the head of a linked list and a number n, rotate the linked list by n spaces +def rotate_linked_list(head:'node', n:int)->'list': + + # if linked list is None or length of 1 or n is negative + # just return head + if head is None or head.next is None or n <= 0: + return head + + # get length of list + length = get_linked_list_length(head) + + # get new tail + tail = head + while tail.next: + tail = tail.next + + # optimize rotation to account for looping through entire list multiple times + n = n % length + + # if n == 0, we don't need to rotate anything + if n == 0: + return head + + curr = head + for i in range(length - n - 1): + curr = curr.next + + # update necessary pointers + new_head = curr.next + curr.next = None + tail.next = head + + return new_head \ No newline at end of file