class Node():
def __init__(self,data):
self.data = data
self.next = None
class Single_LinkedList():
def __init__(self):
self.__head = None
def is_empty(self):
#判断链表是否为空
return self.__head == None
def length(self):
#计算链表长度
cur = self.__head
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self):
#遍历链表
cur = self.__head
while cur != None:
print(cur.data, end=' ')
cur = cur.next
def add(self,data):
#链表头部添加一个元素
node = Node(data)
if self.is_empty():
self.__head = node
else:
node.next = self.__head
self.__head = node
def append(self,data):
#链表尾部插入一个元素
node = Node(data)
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next != None:
cur = cur.next
cur.next = node
def insert(self,pos,data):
#某个位置添加一个元素
node = Node(data)
count = 0
pre = self.__head
if self.is_empty():
self.add(data)
elif pos > self.length()-1:
self.append(data)
else:
while count < (pos - 1):
pre = pre.next
count += 1
node.next = pre.next
pre.next = node
def remove(self,data):
#删除一个元素
pre = None
cur = self.__head
while cur != None:
if data == cur.data:
if cur == self.__head:
self.__head = cur.next
else:
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
def search(self,data):
#查找元素是否存在
cur = self.__head
while cur != None:
if cur.data == data:
return True
else:
cur = cur.next
return False
if __name__ == '__main__':
node = Node(20)
single_linkedlist = Single_LinkedList()
print(single_linkedlist.is_empty())
single_linkedlist.insert(1,20)
single_linkedlist.insert(2,50)
single_linkedlist.append(60)
single_linkedlist.add(100)
print(single_linkedlist.length())
single_linkedlist.travel()
print('\n')
print(single_linkedlist.search(10))
print(single_linkedlist.search(100))
single_linkedlist.remove(50)
single_linkedlist.travel()
single_linkedlist.remove(100)
print('\n')
single_linkedlist.travel()
single_linkedlist.remove(60)
print('\n')
single_linkedlist.travel()
单链表基本操作(增删改查)Python版本
最新推荐文章于 2022-01-29 23:05:12 发布