实现有序链表时,数据项的相对位置取决去它们之间的“大小”比较,若数据项是非数值类型,则需先定义__gt__或__lt__方法,使任何非数值类型能够进行比较;
class...
def __gt__(self, orther):
return self > orther
有序链表与无序链表相比,改变最大的地方是 add() 和 search() 方法:
Node 类:
class Node:
def __init__(self,item):
self.item = item
self.next = None
def getdata(self):
return self.item
def getnext(self):
return self.next
def setdata(self,newitem):
self.item = newitem
def setnext(self,newnext):
self.next = newnext
OrderedList 类:
class OrderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def size(self):
current = self.head
count = 0
while current != None:
count += 1
current = current.getnext()
return count
def search(self,item):
current = self.head
found = False
stop = False #若查找的数据项不在链表中且小于表中某个数据项,可以中断循环
while current != None and not found and not stop:
if current.getdata() == item:
found = True
elif current.getdata() > item:
stop = True
else:
current = current.getnext()
return found
def add(self,item):
temp = Node(item)
current = self.head
previous = None
while current != None and current.getdata() < item:
#循环条件中的 current != None 用于处理尾节点的数据项小于item的情况
previous = current
current = current.getnext()
if previous == None:
#空链表 或 item < self.head.getdata()
temp.setnext(self.head)
self.head = temp
else:
temp.setnext(current)
previous.setnext(temp)
def remove(self,item):
current = self.head
previous = None
found = False
stop = False
while current != None and not found and not stop:
if current.getdata() == item:
found = True
elif current.getdata() > item:
stop = True
else:
previous = current
current = current.getnext()
if found == False:
raise KeyError('NO such item :{}'.format(item))
if previous == None:
#待删除的节点是第一个节点
self.head = current.getnext()
else:
previous.setnext(current.getnext())
def index(self,item):
position = 0
current = self.head
found = False
stop = False
while current != None and not found and not stop:
if current.getdata() == item:
found = True
elif current.getdata() > item:
stop = True
else:
current = current.getnext()
position += 1
if found == True:
return position
else:
raise KeyError('NO such item :{}'.format(item))
def pop(self,position):
# 规定:0代表第一个节点,1代表第二个节点...
current = self.head
previous = None
count = 0
found = False
while current != None and not found:
if count == position:
found = True
else:
previous = current
current = current.getnext()
count += 1
if found == False:
return
elif count == 0:
#pop头节点
self.head = current.getnext()
else:
previous.setnext(current.getnext())