Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphoarty/034f4d79a073da801e33a738e0f8bc05 to your computer and use it in GitHub Desktop.
Save graphoarty/034f4d79a073da801e33a738e0f8bc05 to your computer and use it in GitHub Desktop.
'''
Rotating the Linked List
1. Convert the Linked List into a Circular Linked List
by joining the last node with the root.
2. Move the root the amount of positions needed to be
changed
3. Disconnect the last element counting the length from
the new root.
'''
# The Node
class Node:
def __init__(self, data):
self.data = data
self.next = None
print("New Node : {}".format(data))
# Function to rotate the Linked List
def rotateList(root, skip):
print("Rotate by {}".format(skip))
length = 0
# Use a decoy
node = root
# Connecting the ends
while node.next is not None:
length += 1
node = node.next
node.next = root
# Move the root
for x in range(0, skip):
root = root.next
# Use a decoy
node = root
# Break the end Connection
for x in range(0, length):
node = node.next
node.next = None
return root
# The Main Function
def main():
print("Rotate a Linked List")
root = Node(1)
add(root, Node(2))
add(root, Node(3))
add(root, Node(4))
add(root, Node(5))
add(root, Node(6))
print("Before Rotation")
printList(root)
root = rotateList(root, 2)
print("After Rotation")
printList(root)
# Function to add nodes to the Linked List
def add(root, node):
while root.next is not None:
root = root.next
root.next = node
# Function to print the Linked List
def printList(root):
print("The List is ", end="")
while root is not None:
print("{}".format(root.data), end="")
if root.next is not None:
root = root.next
print(" -> ", end="")
else:
break
print()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment