import operator
class LList:
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def __init__(self):
self.head = None
self.tail = None # initializing the tail
self.nVals = 0
def addFront(self, val):
new_node = self.Node(val, self.head)
if self.head == None:
self.tail = new_node
self.head = new_node
self.nVals += 1
def getFront(self):
if self.head is None:
return None
else:
return self.head.val
def removeFront(self):
if self.head is not None:
if self.tail == self.head: # If the tail and the head ispointing to the same node, then the list has only one node. The reference mustbe removed from both: the tail and the head
self.head = self.tail = None
else:
self.head = self.head.next
self.nVals -= 1
def print(self):
node = self.head
while node is not None:
print(node.val, "--> ", end="")
node = node.next
print("*")
# We modified the addBack() from the tutorial slides to make it O(1) instead of O(N)
def addBack(self, val):
if self.head is None:
self.addFront(val)
else:
self.tail.next = self.Node \
(val) # The while loop to reach the tail is not necessary anymore, we can be replace it with the tail node.
self.tail = self.tail.next
# The tail must be changed to thelast node that we just added to the end of the linked list
self.nVals += 1
# This is the method that answers the question.
def addSorted(self, val):
# If the linked list is empty add the first node. or if the head value is more that the inserted value add it as the new head.
if self.head == None or self.head.val > val:
self.addFront(val)
# else if the tail value is less that the added value, add the new value as the new tail.
elif self.tail.val < val:
self.addBack(val)
# else loop through the nodes until you find the correct place.
else:
current_node = self.head
while current_node.next.val < val:
current_node = current_node.next
current_node.next = self.Node(val, current_node.next)
#########################add##############################################
def printSLL(self):
node = self.head
if node is not None:
while node is not None:
print(node.val, "-->", end="")
node = node.next
print("end")
else:
print("Empty Linked List")
def locate(self, item):
node = self.head
flag = 0
while node is not None:
if node.val == item:
flag = 1
else:
flag = 0
node=node.next
if flag == 0:
print("Item was not located")
else:
print("Item was located")
L = LList()
# L=None
for i in range(1, 10):
L.addFront(i)
L.printSLL()
L.locate(2)
[笔记]python链表
最新推荐文章于 2024-11-10 08:15:38 发布