class Node():
def __init__(self, value=None, next=None):
self.__value = value
self.__next = next
def getValue(self):
return self.__value
def getNext(self):
return self.__next
def setValue(self, newValue):
self.__value = newValue
def setNext(self, nexNext):
self.__next = nexNext
class Link():
def __init__(self):
self.__head = Node() #头结点,不存放元素,哨兵节点
self.__tail = None
self.__length = 0
def isEmpty(self):
'''
判断链表是否为空
:return:
'''
return self.__head.getNext() == None
def add(self, value):
'''
头插法插入元素
:param value:
:return:
'''
newnode = Node(value, None)
newnode.setNext(self.__head.getNext())
self.__head.setNext(newnode)
def append(self, value):
'''
尾插法插入元素
:param value:
:return:
'''
newnode = Node(value)
if self.isEmpty():
self.__head.setNext(newnode)
else:
current = self.__head.getNext()
while current.getNext() != None:
current = current.getNext()
current.setNext(newnode)
def search(self, value):
'''
查找链表中是否含有该元素
:param value:
:return:
'''
current = self.__head
foundvalue = False
while current != None and not foundvalue:
if current.getValue() == value:
foundvalue = True
else:
current = current.getNext()
return foundvalue
def index(self, value):
'''
查找该元素在链表中的下标位置,
若没有则返回None
:param value:
:return:
'''
current = self._head
count = 0
found = None
while current != None and not found:
count += 1
if current.getValue() == value:
return count
return None
def print(self):
'''
打印链表元素
:return:
'''
current = self.__head.getNext()
while current != None:
print(current.getValue())
current = current.getNext()
def delete(self, value):
'''
删除指定元素
:param value:
:return:
'''
current = self._head
while current.getNext() != None and current.getNext().getValue() != value:
current = current.getNext()
if current.getNext() == None:
return 0 #链表中无此元素,删除失败
else:
r = current.getNext()
current.setNext(r.getNext())
del r
return 1
Python链表操作
最新推荐文章于 2024-09-09 16:39:53 发布