# 链表的基本组成就是一个个Node,每个Node都包括两部分内容,一部分是自身的data,另一部分是下一个Node的索引
# 每一个链表都有一个Head节点和一个End节点,End节点的next为None
class Node:
def __init__(self,init_data):
self.data = init_data
self.next = None
def get_data(self):
return self.data
def set_data(self,new_data):
self.data = new_data
def get_next(self):
return self.next
def set_next(self,new_next):
self.next = new_next
class UnorderList:
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def add(self,item):
temp = Node(item) # 创建新节点
temp.next = self.head # 将新节点链接之前的链表
self.head = temp # 将新节点设为head
def size(self):
current = self.head
count = 0
while(current != None):
count += 1
current = current.get_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())
class orderList:
def __init__(self): # 无变化
self.head = None
def is_empty(self): # 无变化
return self.head == None
def add(self,item): # 变化最大的在这里
current = self.head
previous = None
stop = False
while(current != None and not stop):
if current.get_data() > item:
stop = True
else:
previous = current
current = current.get_next()
temp = Node(item)
if previous == None:
temp.set_next(self.head)
self.head = temp
else:
temp.set_next(current)
previous.set_next(temp)
def size(self): #无变化
current = self.head
count = 0
while(current != None):
current += 1
current = current.get_next()
return count
def search(self,item): #其实没变化,stop可有可无
current = self.head
found = False
stop = False
while(current != None and not found and not stop):
if current.get_data() == item:
found = True
else:
if current.get_data() > item:
stop = 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())