1. python实现单链表
class Node:
'''
节点类, 用于存储数据和地址
'''
def __init__(self, data, next=None):
self._data = data
self._next = next
def __repr__(self):
return str(self._data)
class ChainTable:
'''
链表类, 实现添加元素方法
'''
def __init__(self, head=Node(None), length=0):
self.head = head
def is_empty(self):
# 判断是否为空
return self.head._data == None
def append(self, data):
# 在链表末尾插入元素
# 判断插入的数据类型
if not isinstance(data, Node):
data = Node(data)
# 判断带插入的链表长度
if self.is_empty():
self.head = data
else:
curr = self.head
while(curr._next):
curr = curr._next
curr._next = data
def __repr__(self):
node = self.head
result = []
while node:
result.append(node._data)
node = node._next
return str( result )
if __name__ == '__main__':
temp = ChainTable()
temp.append(1)
temp.append('2')
temp.append('4444')
print('链表:', temp)
运行结果:
2. 链表从尾到头打印
def print_reval(l):
curr = l.head
result = [curr._data]
while curr._next:
curr = curr._next
result.insert(0, curr._data)
return result
if __name__ == '__main__':
print(temp)
print(print_reval(temp))
3. 链表中倒数第k个节点(k = 3)
def the_last_k_elemt(l, k):
node1, node2 = l.head, l.head
for _ in range(k):
node1 = node1._next
while node1._next:
node1 = node1._next
node2 = node2._next
return node2._next._data
if __name__ == '__main__':
print(the_last_k_elemt(temp, 4))
4. 翻转链表
from copy import deepcopy
def reverse_linked_list(l):
l = deepcopy(l)
post = Node(None)
curr = l.head
while curr._next:
next = curr._next
curr._next = post
post = curr
curr = next
l.head = curr
curr._next = post
return l
if __name__ == '__main__':
print(reverse_linked_list(temp))
5. 合并两个单调递增链表
def merge_linked_list_1(*args):
args = list(args)
result_linked_list = ChainTable()
out = result_linked_list.head
while args:
min = int(np.argmin([i._data for i in args]))
if out._data == None:
out._data = args[min]._data
# out = deepcopy(args[min]) # 仍然想不通这句为什么出错
else:
out._next = args[min]
out = out._next
if not args[min]._next:
args.pop(min)
else:
args[min] = args[min]._next
return result_linked_list
if __name__ == '__main__':
a = ChainTable()
b = ChainTable()
a.append(1)
a.append(3)
a.append(5)
a.append(6)
b.append(2)
b.append(4)
b.append(7)
b.append(8)
result = merge_linked_list_1(a.head, b.head)
print(result)