直接上代码,如下:
#encoding:utf-8
class Node():
# 设置节点
def __init__(self, data=None, next=None): # 传入值和指针
self.data = data
self.next = next
class SingleLinkList():
def __init__(self):
self.head = None
def print(self):
# 打印列表
if self.head is None:
print("LinkedList is empty") # 空链表
return
itr = self.head
litr = "" # 初始化链表
while itr:
litr += str(itr.data) + "--" # 拼接链表
itr = itr.next # 指针后移
print(litr)
def get_length(self):
# 获取链表长度
lens = 0
itr = self.head
while itr:
lens += 1
itr = itr.next
return lens
def insert_at_start(self, data):
node = Node(data, self.head) # 实例化一个待插入的结点
self.head = node # 把实例化的新结点插在头结点上
def insert_at_end(self, data):
if self.head is None:
self.head = Node(data, None) # #当链表为空时,把实例化的结点做为头结点,注意此时结点也是为尾结点,故指针为None
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data, None) # 实例化一个结点插到链表尾部
def insert_at(self, index, data):
if index < 0 or index > self.get_length(): # 越界
raise Exception("Invalid Index")
if index == 0: # 在第一个位置插入结点
self.insert_at_start(data)
return
count = 0
itr = self.head
while itr:
if count == index - 1:
node = Node(data, itr.next) # 实例化一个新的结点,新的结点的指针指向当前itr的下一个结点
itr.next = node
break
itr = itr.next
count += 1
def remove_at(self, index):
if index < 0 or index >= self.get_length():
raise Exception("Invalid Index")
if index == 0:
self.head = self.head.next # 只需把头结点的指针往后移动一个即可
return
count = 0
itr = self.head
while itr:
if count == index - 1:
itr.next = itr.next.next # itr的指针指向它的下下个结点
break
itr = itr.next
count += 1
def insert_values(self, data_list):
self.head = None
for data in data_list:
self.insert_at_end(data) # 在尾部依次插入
def insert_after_value(self, data_after, data_to_insert):
if self.head is None:
return
if self.head.data == data_after:
self.head.next = Node(data_to_insert, self.head.next)
return
itr = self.head
while itr:
if itr.data == data_after:
itr.next = Node(data_to_insert, itr.next)
break
itr = itr.next
def remove_by_value(self, data):
if self.head is None:
return
if self.head.data == data:
self.head = self.head.next
return
itr = self.head
while itr.next:
if itr.next.data == data:
itr.next = itr.next.next
break
itr = itr.next
ll = SingleLinkList()
ll.insert_values(['aa', 'bb', 'cc', 'dd']) # 插入一堆元素
ll.insert_at(1, "ee") # 某一位置插入一个元素
ll.print() # 打印当前链表 aa--ee--bb--cc--dd--
ll.remove_at(2) # 删除某一位置元素
ll.print() # 打印当前链表 aa--ee--cc--dd--
ll2 = SingleLinkList()
ll2.insert_values([1, 2, 3, 4, 5])
ll2.insert_at_end(6)
ll2.print() # 1--2--3--4--5--6--