8.12 LAB: Output a linked list Write a recursive function called print_list() that outputs the integer value of each nod

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

8.12 LAB: Output a linked list Write a recursive function called print_list() that outputs the integer value of each nod

Post by answerhappygod »

8.12 LAB: Output a linked list
Write a recursive function called print_list() that outputs theinteger value of each node in a linked list. Function print_list()has one parameter, the head node of a list. The main program readsthe size of the linked list, followed by the values in the list.Assume the linked list has at least 1 node.
Ex: If the input of the program is:
the output of the print_list() function is:
Hint: Output the value of the current node, then call theprint_list() function repeatedly until the end of the list isreached. Refer to the Node class to explore any available instancemethods that can be used for implementing the print_list()function.
THIS IS THE PROMPT I WAS GIVEN
class Node: def __init__(self, value): self.data_val = value self.next_node = None
def insert_after(self, node): tmp_node = self.next_node self.next_node = node node.next_node = tmp_node
def get_next(self): return self.next_node
def print_data(self): print(self.data_val, end=", ") def print_list(head_node): if head_node is None: return else: head_node.print_data() print_list(head_node.next_node)
# TODO: Write recursive print_list() function here.
if __name__ == "__main__": size = int(input()) value = int(input()) head_node = Node(value) # Make head node as the firstnode last_node = head_node # Insert the second and the rest of the nodes for n in range(1, size): value = int(input()) new_node = Node(value) last_node.insert_after(new_node) last_node = new_node temp = head_node print_list(head_node)
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply