1 class Node: 2 definit_(self, value): self.value = value self.nextNone 4 5 6 cl
ID: 3699829 • Letter: 1
Question
1 class Node: 2 definit_(self, value): self.value = value self.nextNone 4 5 6 class LinkedList: 7 def init__(self): self, first = None 10 def prepend(self, value): new-node = Node(value) new-node . next- self. first self.first-new_node 12 14 15 def reverse(self 16 17 18 19 20 21 p None currentself.first while current is not None: ncurrent.next current.next = p p = Current current- n self.first p 23 24 25 def printItems(self): 26 27 28 29 30 31 my-list-LinkedList() 32 my_list.prependC"a") currentself.first while current is not None: print(current.value, end"" currentcurrent.nextExplanation / Answer
the code first defines a class Node, which has attributes value and none,it has a constructor that specifies the value of value and next.Basically, this creates a node, which will be linked after one another in the next class then a class LinkedList is created for making linked list of nodes object using the class Node it has an attribute first, which contains the first Node object of the linked list the constructor def__init(self): is initializing first node to None, since we havennt added any node to the linked list the class LinkedList has a function prepend, which is used to add nodes to the list from the start it creates a new node using value provided, and the nex attribute of this node stores the firs node of or linked list. Then this new node is assigned to first attribute, as a result this new node is successfully prepended the function reverse is used to reverse the order of linked list, it starts fromthe beginning ofthe list and moves along reversing the link of 2 between 2 nodes at a time function printitems prints all the nodes in a linked list. It iterates from the first node until a node with next= None is reached
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.