# Node类
class Node():
def __init__(self, initdata):
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
# 无序列表
# UnorderedList类
class UnorderedList():
def __init__(self):
self.head = None
# 判断列表是否为空
def isEmpty(self):
return self.head == None
# 在列表中添加元素item
def add(self, item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
# 计算出列表长度
def length(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
# 搜索列表中的item元素,找到返回True,否则返回False
def search(self, item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
# 移除元素item
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:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
# 有序列表
class OrderedList():
def __init__(self):
self.head = None
# 搜索元素item
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
else:
if current.getData() > item:
stop = True
else:
current = current.getNext()
return found
# 添加元素item
def add(self, item):
current = self.head
previous = None
stop = False
while current != None and not stop:
if current.getData() > item:
stop = True
else:
previous = current
current = current.getNext()
temp = Node(item)
if previous == None:
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
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
def isEmpty(self):
return self.head == None
def length(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
Python数据结构—列表定义
最新推荐文章于 2024-07-26 21:19:18 发布