最近在用python刷leetcode,遇到了链表的问题,特地研究了一下python是如何表示链表以及对链表的简单操作。
代码如下:
'''
用python实现简单的链表操作
包括链表的增、删、查
'''
class Node(object):
# 初始化节点数据,next ==> null
def __init__(self,data):
self.data = data
self.next = None
# 获取节点的数据
def getData(self):
return self.data
# 设置节点的数据
def setData(self,new_data):
self.data = new_data
# 返回后继节点
def getNext(self):
return self.next
# 更新后继节点
def setNext(self,new_Next):
self.next = new_Next
class LinkList(object):
# 初始化头节点,节点空
def __init__(self):
self.head = None
# 添加节点,使之成为新的头节点
def addNode(self,data):
new_Node = Node(data)
new_Node.setNext(self.head)
self.head = new_Node
# 查找相关节点,判断data在链表中是否出现
def searchNode(self,data):
checking = self.head # 从头节点开始查找
while checking != None:
if checking.getData() == data: # 查找到,则返回True
return True
checking = checking.getNext() # 查找下一个节点
return False # 遍历到最后未查找到相关的节点,返回False
# 删除节点
def removeNode(self,data):
checking = self.head # 从头节点开始查找
previous = None # 记录前一个节点,便于删除某节点后指向后面的节点
while checking != None:
if checking.getData() == data:
break
previous = checking # previous 指向checking更新前的一个节点
checking = checking.getNext() # checking指向下一个节点
if previous == None: # 如果是第一个节点找到的,那就把self.head指向checking.next
self.head = checking.getNext()
else:
previous.setNext(checking.getNext())
# 判断链表是否为空
def isEmpty(self):
return self.head == None
# 返回链表的长度
def size(self):
count = 0
checking = self.head
while checking != None:
count += 1
checking = checking.getNext()
return count
if __name__ == '__main__':
l = LinkList()
for i in range(10):
l.addNode(i)
l.removeNode(9)
l.removeNode(3)
print(l.size())