类的声明:
节点
class node: # 这里不用加括号,具体参数都在init函数里,这也是和函数区别的一部分,函数的升级和高级有序集合
def __init__(self, val):
self.data = val
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 isEmpty(self):
return self.head == None
def add(self, item): # 由于是从首向尾遍历,那么自然是向首添加元素方便
newNode = node(item)
newNode.setNext(self.head)
self.head = newNode
def size(self):
count = 0
p = self.head
while p != None:
count = count + 1
p = p.getnext()
return count
def search(self, content):
p = self.head
found = False # 大写!!有了found这个较为特殊的变量时,代码更加易读清晰
while p != None and not found:
if p.getData == content:
found = True
else:
p = p.getnext()
return found
def remove(self, content):
previous = None
current = self.head
found = False
while current != None and not found:
if current.getData() == content:
found = True
else:
previous = current
current = current.getnext()
if found:
if previous == None:
self.head = self.head.getnext()
else:
previous.setNext(current.getnext())
def append(self, content): # 在末尾加
newNode = node(content)
current = self.head
previous = None
while current != None:
previous = current
current = current.getnext()
if previous != None:
previous.setNext(newNode) # 注意这是函数而不是参数不能用等于,而且修改对象(这里是node)的参数也只能通过方法
else:
current.head = newNode # 一定要区分上面的的if
def pop(self): # 删掉链尾的元素
current = self.head
if current.getnext == None:
print("Error: List is empty!")
else:
previous = None
while current.getnext():
previous = current
current = current.getnext()
previous.setNext(None)
def printList(self):
p = self.head
while p:
print(p.data)
p = p.getnext()
MyList = unorderList()
MyList.add(1)
MyList.add(2)
MyList.add(3)
MyList.add(4)
MyList.pop()
MyList.append(1) # pop和append抵消了
MyList.remove(3)
print("search answer is ", MyList.search(3))
print("MyList's size is %d" % MyList.size())
MyList.printList()