这是在python中。
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.get_data() == item:
found = True
else:
current = current.get_next()
return found
这是搜索功能的代码
完整的LL实施:
from Node import Node
class linked_list:
def __init__(self):
self.head = None
def add(self, data):
node = Node(data)
if(node != None):
node.next = self.head
self.head = node
def append(self, data):
node = Node(data)
if(node != None):
if(self.head == None):
self.head = node
else:
trav = self.head
while(trav.next != None):#find last node
trav = trav.next
trav.next = node
def size(self):
count = 0
temp = self.head
while(temp != None):
count = count + 1
temp = temp.next
return count
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.get_data() == item:
found = True
else:
current = current.get_next()
return found
def remove(self, item):
current = self.head
previous = None
found = False
while not found:
if current.get_data() == item:
found = True
else:
previous = current
current = current.get_next()
if previous == None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
#insert(pos, item) – adds item to position pos >= 1.
def insert(self, pos, item):
size = self.size()
if(pos <= 0 or (size - pos )< -1):
print("Not enough items in list to insert in that position. Size =",\
size, "position = ", pos)
return False
if(pos == 1):
newNode = Node(item)
newNode.next = self.head
self.head = newNode
else:
count = 2
probe = self.head
while(probe != None and count != pos):
probe = probe.next
count += 1
newNode = Node(item)
newNode.next = probe.next
probe.next = newNode
return True
#popFirst() – removes and returns the first item in the list.
def popFirst(self):
if (self.head == None):
return None
else:
curr = self.head
self.head = self.head.next
return curr.data
#pop() – removes and returns the last item in the list.
def pop(self):
if (self.head == None):
return None
else:
curr = self.head
prev = None
while(curr.next != None):
prev = curr
curr = curr.next
if(prev == None):#only 1 item in the list
head = None
return curr
else:
prev.next = None
return curr
def printList(self, msg):
temp = self.head
print(msg, end = ": ")
while(temp != None):
print(temp.data, end=" ")
temp = temp.next
print()
def isEmpty(self):
return head.next == None
def peek(self):
if Node.next == None:
return False
else:
return Node.data
由于