CSStudyprogram.py - #Linked Lists = =#memory notes#are not...

This preview shows page 1 - 3 out of 7 pages.

#Linked Lists ========================================================================================================================#memory notes#are not good at inspection#good with insertion without big memory load#linked listwll aways need to search from head even if sorted#This is how to make a node class for a linked list class Node():def __init__(self,data = None):self.__data = dataself.__next = Nonedef getData(self):return self.__datadef setData(self,data):self.__data = datadef getNext(self):return self.__nextdef setNext(self,next):self.__next = next#overloading operator for a string for the Nodedef __str__(self):return "A node with data: "+str(self.__data)#This is how to make a linked list class for the Nodesclass LL():def __init__(self,head=None):self.__head = head#The string representation of a linked list will print out all elements in the linked list# The method will set the variable "current" to the head of the list#then the method will print out the data in the head and#then set the current variable to the next node (which can be found in the next attribute of the current node)#It will stop searching once the current is turned to none, meaning that thenext attrbute was Nonedef __str__(self):current = self.__headmystr = ""counter = 0while current !=None:counter +=1mystr = mystr + "Node" + str(counter) + ": " + str(current.getData()) + "\n"current = current.getNext()return mystr#This metod overrides the "[]" syntax and it is used to find certain nodes in the linked list#THE THOUGHT PROCESS#First checks to see if the index is out of bounds by seeing if it less thanzero or greater than the amount of Nodes#Then it sets the variable current to the head#The counter is set to 0#The if the counter is less than the index, then current is set to the next node#once the counter is greater than the index then it wil return current#for example if you ask for [0] it wll return the first node beacause the counter is equal to the index#for example if you ask for [5] it will return the 6th node 0,1,2,3,4,5 because 5 is equal to 5 and not less than#the < operator is used to make sure that you get the node on the index thatis called
def __getitem__(self,index):if index < 0 or index >= len(self):print ("Index out of bounds")returncurrent = self.__headcounter = 0while counter < index:counter +=1current = current.getNext()return current#This overrides the len operator#The thought process#sets the current varibale as the head and it will add to counter if next isnot None#This means that if the head node has next as None then the counter is ONE#This means that if the 5th node has next as None then the counter will go up to 5#COUNTS AS 1 2 3 4 5...

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture