Professional Documents
Culture Documents
Link List
Link List
Head of Node
a pointer/reference next node
Head of pointer
End of Node = None
mylist.add(31)
mylist.add(77)
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class UnorderedList:
class UnorderedList: Head-> None
def __init__(self):
self.head = None
def show(self):
current = self.head
print ('Head ->', end="")
while current != None:
print (current.getData(), end=" -> ")
current = current.getNext()
print ('None’)
def isEmpty(self):
return self.head == None
Add Link List def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
mylist.show()
mylist.add(26)
mylist.add(54)
Mylist.show()
Size, Search & Remove Link List
linked list traversal = process of systematically visiting each node
As we visit each node, we move the reference to the next
node by “traversing” the next reference.
def size(self):
current = self.head
count = 0
count = count + 1
current = current.getNext()
return count
Search
• the traversal is initialized to start at the head
• use a boolean variable called found, Since we have not found the item
at the start of the traversal, found can be set to False
• The iteration (both conditions : there are more nodes to visit and we
have not found the item we are looking for)
if whether the data = the current node found can be set
to True.
else continue to check the next node
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
print('Data in List')
else:
current = current.getNext()
return found
Remove
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
current = current.getNext()
print ("None")
def isEmpty(self):
return self.head == None
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
print('Data in List')
else:
Double Link List
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
temp.setPrev(None)
next = temp.getNext()
if next != None:
next.setPrev(temp)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
print('Data in List')
else: