无序表
class Node:
def __init__(self, nitdata):
self.data = initdata
self.next = None
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 UnorderList:
def __init__(self):
self.head = None
def add(self,item): # 把数据添加到表头
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self): # 从链条头head开始遍历到表尾同时用变量累加经过的节点个数
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
def search(self,item): # 从链表头head开始遍历到表尾,同时判断当前节点的数据项是否目标
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
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: # 若previous为none,则找到的节点是头节点
self.head = current.getNext() # 把头节点指向要删除节点的下一个,就删除了头节点
else: # 若找到的节点不是头节点,就把previous设为要删除节点的下一个,把要删除节点绕过去
previous.setNext(current.getNext())
有序表
class OrderedList:
# isEmpty,size,remove等与次序无关,与无序表实现一样
# search,add方法需要修改
def __init__(self):
self.head = None
def search(self,item): # 从链表头head开始遍历到表尾,同时判断当前节点的数据项是否目标
current = self.head
found = False
stop = False
while current != None and not found and not stop:
if current.getData() == item:
found = True
else:
if current.getData() > item: # 当当前节点大于item时,就停止搜索节点
stop = True
else:
current = current.getNext()
return found
def add(self,item):
current = self.head
previous = None
stop = False
# 发现插入位置,此时要维护previous的使用
while current != None and not stop:
if current.getData() == item:
stop = True
else:
previous = current
current = current.getNext()
temp = Node(item)
if previous == None: # 若要插入在表头,此时previous为none,
temp.setNext(self.head) # 将新插入节点的next指向表头
self.head = temp # 把表头指向新插入节点
else: # 若插在中间
temp.setNext(current) # 将新插入节点的next指向现在节点
previous.setNext(temp) # 把新插入节点设为previous的下一个