145k views
4 votes
Given main.py and a Node class in Node.py, complete the LinkedList class (a linked list of nodes) in LinkedList.py by writing the insert_in_ascending_order() method that inserts a new Node into the LinkedList in ascending order.

Click the orange triangle next to "Current file:" at the top of the editing window to view or edit the other files.

Note: Do not edit any existing code in the files. Type your code in the TODO sections of the files only. Modifying any existing code may result in failing the auto-graded tests.

Important Coding Guidelines:

Use comments, and whitespaces around operators and assignments.
Use line breaks and indent your code.
Use naming conventions for variables, functions, methods, and more. This makes it easier to understand the code.
Write simple code and do not over complicate the logic. Code exhibits simplicity when it’s well organized, logically minimal, and easily readable.
Ex: If the input is:

8 3 6 2 5 9 4 1 7
the output is:

1 2 3 4 5 6 7 8 9
CODE: from Node import Node
from LinkedList import LinkedList

if __name__ == "__main__":
int_list = LinkedList()

user_input = input()

# Convert the string tokens into integers and insert into intList
tokens = user_input.split()
for token in tokens:
num = int(token)
new_node = Node(num)
int_list.insert_in_ascending_order(new_node)

int_list.print_list()

User Unigeek
by
8.0k points

1 Answer

1 vote

Answer:

class LinkedList:

def __init__(self):

self.head = None

def insert_in_ascending_order(self, new_node):

"""Inserts a new node into the linked list in ascending order.

Args:

new_node: The node to insert.

Returns:

None.

"""

# If the linked list is empty, set the new node as the head.

if self.head is None:

self.head = new_node

return

# Find the insertion point.

current = self.head

while current.next is not None and current.next.data < new_node.data:

current = current.next

# Insert the new node.

new_node.next = current.next

current.next = new_node

def print_list(self):

"""Prints the linked list in order.

Returns:

None.

"""

current = self.head

while current is not None:

print(current.data)

current = current.next

User SaltySea
by
7.2k points