Lab 4

.docx

School

Toronto Metropolitan University *

*We aren’t endorsed by this school

Course

305

Subject

Chemistry

Date

Jan 9, 2024

Type

docx

Pages

4

Uploaded by JusticeStarWaterBuffalo329

Lab 4.py # Sahib Gaba # 500927758 class Node: def __init__ ( self , dataval= None ): self .dataval = dataval self .nextval = None self .prevval = None class LinkedList: def __init__ ( self ): self .headval = None def __str__ ( self ): node = self .headval output = "[ " while (node != None ): output = output + str (node.dataval) + ", " node = node.nextval if ( len (output) > 2 ): output = output[:- 2 ] return output + " ]" # DO NOT EDIT ANY CODE ABOVE THIS LINE def insert( self , val): node=Node(val) if self .headval is None : self .headval=node return end= self .headval while (end.nextval): end=end.nextval end.nextval=node # Fill in this method, which takes a value and adds a node which holds the value at the end of the linked list def delete( self , index= 0 ): curr_node = self .headval pointerIndex= 0 if pointerIndex == index: self .headval=curr_node.nextval curr_node = None return prev = None while curr_node is not None and pointerIndex!= index: pointerIndex+= 1 prev = curr_node curr_node=curr_node.nextval if curr_node is None : return prev.nextval=curr_node.nextval curr_node = None # Fill in this method, which takes an index(with a default value of 0), and deletes the node at the index specified def find( self , val): curr_node= self .headval
pointerIndex= 0 if curr_node.dataval == val: return pointerIndex while curr_node is not None and curr_node.dataval != val: pointerIndex+= 1 curr_node = curr_node.nextval if curr_node is None : prev = curr_node return False return pointerIndex # Fill in this method, which takes in a value and returns the index of the first node which contains that value. If no node containing that value is found, return False def reverse( self ): curr_node = self .headval prev = None while curr_node is not None : next=curr_node.nextval curr_node.nextval=prev prev=curr_node curr_node=next self .headval=prev # Fill in this method, which reverses the list # DO NOT EDIT ANY CODE PAST THIS LINE # Tests # Insertion Test a = LinkedList() a.insert( 1 ) a.insert( 2 ) a.insert( 'a' ) a.insert( 3 ) print ( str (a) == "[ 1, 2, a, 3 ]" ) # Deletion a.delete() print ( str (a) == "[ 2, a, 3 ]" ) a.delete( 2 ) print ( str (a) == "[ 2, a ]" ) # Find a.insert( 'b' ) a.insert( 'c' ) a.insert( 'b' ) print (a.find( 'b' ) == 2 ) print (a.find( 'c' ) == 3 ) print (a.find( 'd' ) == False ) # Reverse a.reverse() print ( str (a) == "[ b, c, b, a, 2 ]" ) # Singly Linked Lists Tests class DoublyLinkedList: def __init__ ( self ): self .headval = None def __str__ ( self ): node = self .headval
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help