Skip to content

Add length and rotate method to linkedlist.py #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions easyPythonpi/methods/linkedlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -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