Complete the below code so the program will : - Receive a word from user - Then, transfers it into a doubly linked list (for example if the word is Hello, then the doubly linked list would have 5. nodes: H, e, l , l , o) - Finally, uses insertion-sort to scramble it into descending order. - Example: If the word is "Hello", the output should look like below: - List after insertion sort: o l l h e Some of the code has been written below in main.py
Complete the below code so the program will : - Receive a word from user - Then, transfers it into a doubly linked list (for example if the word is Hello, then the doubly linked list would have 5. nodes: H, e, l , l , o) - Finally, uses insertion-sort to scramble it into descending order. - Example: If the word is "Hello", the output should look like below: - List after insertion sort: o l l h e
Some of the code has been written below in main.py
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
# Empty Doubly Linked List
class DoublyLinkedList:
def __init__(self):
self.head = None
# Inserts a new node on the front of list
def append(self, new_data):
if self.head is None:
self.head = new_data
self.tail = new_data
else:
self.tail.next = new_data
new_data.prev = self.tail
self.tail = new_data
def printList(self):
if(self.head is None):
print('Empty!')
else:
node = self.head
while(node is not None):
print(node.data),
node = node.next
print()
def remove(self, current_node):
successor_node = current_node.next
predecessor_node = current_node.prev
if successor_node is not None:
successor_node.prev = predecessor_node
if predecessor_node is not None:
predecessor_node.next = successor_node
if current_node is self.head:
self.head = successor_node
if current_node is self.tail:
self.tail = predecessor_node
def insert_after(self, current_node, new_node):
if self.head is None:
self.head = new_node
self.tail = new_node
elif current_node is self.tail:
self.tail.next = new_node
new_node.prev = self.tail
self.tail = new_node
else:
successor_node = current_node.next
new_node.next = successor_node
new_node.prev = current_node
current_node.next = new_node
successor_node.prev = new_node
def prepend(self, new_node):
if self.head == None:
self.head = new_node
self.tail = new_node
else:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
def insertion_sort_doubly_linked(self):
current_node = self.head.next
while current_node != None:
next_node = current_node.next
search_node = current_node.prev
while ((search_node != None) and
(search_node.data < current_node.data)):
search_node = search_node.prev
# Remove and re-insert curNode
self.remove(current_node)
if search_node == None:
current_node.prev = None
self.prepend(current_node)
else:
self.insert_after(search_node, current_node)
# Advance to next node
current_node = next_node
if __name__ == '__main__':
#*** Your code goes here ***
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 4 images