在用python实现链表的时候,从网上参考了很多实现方式。虽然大多编写的非常详细,但是我更需要一个极简的描述!方便深刻理解,然后由简入繁。最后总结如下:
一、定义和初始化(头插法)
主要是节点类和写入数据过程
# 节点类
class Node(object):
def __init__(self,data,next = None):
self.data = data
self.next = None
# 数组,用于转成链表
list1 = [3, 2, 1]
# 头节点
head = Node(None)
# 头插法
for i in range(len(list1)):
s = Node(list1[i])
s.next = head.next
head.next = s
#输出节点内容,输出完后,单链表结构也销毁了
while head != None:
print(head.data)
head = head.next
执行后输出:
二、尾插法
从上面的结果看,输出顺序与数组的顺序相反。如果想要相同顺序,则要采用尾插法,插入过程代码如下:
# 头节点
head = Node(None)
# 尾节点
r = head
# 尾插法
for i in range(len(list1)):
s = Node(list1[i])
r.next = s
r = s
执行后输出:
三、用于计算两数相加
为了展示链表使用过程,拿两数相加来举例。如1024加1111,首先将两个数值按最高位数依次存入数组,然后把数值存入链表,最后将相加结果再存入链表输出。
# 节点类
class Node(object):
def __init__(self,data,next = None):
self.data = data
self.next = None
# 数值1024,按最高位数依次存入数组
list1 = [1, 0, 2, 4]
# 数值1111,按最高位数依次存入数组
list2 = [1, 1, 1, 1]
# 头节点
head1 = Node(None)
head2 = Node(None)
# 头插法,存入数值1024
for i in range(len(list1)):
s = Node(list1[i])
s.next = head1.next
head1.next = s
# 头插法,存入数值1111
for i in range(len(list2)):
s = Node(list2[i])
s.next = head2.next
head2.next = s
# 保存头节点,后面用于遍历
head = head1
tmp = 0
# 跳过头节点
head1 = head1.next
head2 = head2.next
# 计算两数相加
while (head1 is not None or head2 is not None):
sum = head1.data+head2.data+tmp
if sum > 9:
sum -= 10
if head1 is not None:
head1.data = sum
else:
s = Node(sum)
head1.next = s
tmp = 1
else:
head1.data = sum
tmp = 0
head1 = head1.next
head2 = head2.next
# 遍历链表输出
while head != None:
print(head.data)
head = head.next
执行后输出: