Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Test the implementation of the Bag class in Listing 6.5 (page 166) in your book. Your demonstration must include the iterator for the Bag class!
Test the implementation of the Bag class in Listing 6.5 (page 166) in your book.
Your demonstration must include the iterator for the Bag class!
Demonstrate with several examples that the function behaves as expected.
Listing 6.5 The llistbag-py module. 1 # Implements the Bag ADT using a singly linked list. 3 class Bag : 4 # Constructs an empty bag 5 definit.. self): 6 self._head = None 7 self. Size = 0 Returns the number of items in the bag. 10 def --ten_-( self ): 11 return self. Size 12 13 #Determines if an item is contained in the bag. 14 def-contains_ self, target ): 15 cur Node = self._head 16 while curNode is not None and curNode.iten != target : 17 curNode = curNode.next 18 return curNode is not None 19 20 # Adds a new item to the bag. 21 def add( selt, item ): 22 newNode = _BagListNode( iten) newNode. next = self. head Prepend the new rode (See earlier code) self._head = newNode self._size = 1 26 27 Removes an instance of the item from the bag. 28 def removel self, item ): 20 predNode = None 30 curNode = self.head 32 while curNode is not None and curNode.iten != iten: predNode = curNode 33 cur Node = curNode.next 34 35 # The item has to be in the bag to remove it. 36 assert curNode is not None, "The item must be in the bag." 37 38 Untink the node and return the iten 39 self. size - 1 40 if curNode is head: 41 self._head = curNode.next + Special case 42 else: 43 predNode.next = curNode.next 44 return curNode.item 45 46 Returns an Iterator for traversing the list of items. 47 def iter_(self): 48 return BagIterator self._head) 50 # Defines a private storage class for creating list nodes. 51 class BaglistNode object ): 52 definit__(self, iten: 53 self.item = iten 54 self.next = NoneStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started