class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class SingleLinkedList:
def __init__(self, nodes=None):
self.head = None
if nodes is not None:
node = Node(nodes.pop(0))
self.head = node
for elem in nodes:
node.next = Node(elem)
node = node.next # 写成Node(elem)也可以
def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.append(node.data)
node = node.next
nodes.append("None")
return '->'.join(nodes)
def __iter__(self):
cur = self.head
while cur is not None:
yield cur
cur = cur.next
def add_first(self, node):
'''头部插入节点'''
node.next = self.head.next
self.head = node
def add_last(self, node):
'''尾部插入节点'''
if not self.head:
self.head = node
return
# 迭代器
for cur_node in self:
pass
cur_node.next = node
def add_after(self, target_node_data, new_node):
if not self.head:
raise Exception('LList is empty')
for cur_node in self:
if cur_node.data == target_node_data:
new_node.next = cur_node.next
cur_node.next = new_node
return
raise Exception("Node with data '%s' not found" % target_node_data)
def add_before(self, target_node_data, new_node):
if not self.head:
raise Exception('LList is empty')
# 利用for循环的执行顺序去实现prev_node
prev_node = self.head
for cur_node in self:
if cur_node.data == target_node_data:
new_node.next = cur_node
prev_node.next = new_node
return
prev_node = cur_node
raise Exception("Node with data '%s' not found" % target_node_data)
def remove_node(self, target_node_data):
# 边界情况
if not self.head:
raise Exception('LList is empty')
# 删除头节点
if self.head.data == target_node_data:
self.head = self.head.next
return
# 删除头之外节点
prev_node = self.head
for cur_node in self:
if cur_node.data == target_node_data:
prev_node.next = cur_node.next
return
prev_node = cur_node
raise Exception("Node with data '%s' not found" % target_node_data)
# 一个一个节点
llist = SingleLinkedList()
fnode = Node("1")
llist.head = fnode
snode = Node("2")
tnode = Node("3")
fnode.next = snode
snode.next = tnode
# 列表转链表
ltllist = SingleLinkedList(['a', 'b', 'c'])
ltllist.add_before('c', Node('cc'))
print(ltllist)