2019/10/16 以前写的代码太SB了, 今天全部重写了
链表的构造,包括数组转链表, 链表的增删,逆转,两两对调
而且我用是有头链表
class LNode(object):
def __init__(self, data):
self.data = data
self.next = None
class LList(object):
def __init__(self):
self.head = None
def list_node(self, arr):
self.head = LNode(None)
p = self.head
for i in arr:
node = LNode(i)
p.next = node
p = p.next
def print_node(self):
p = self.head
while p:
print(p.data, end="->")
p = p.next
def get_length(self):
p = self.head
tmp = 0
while p:
tmp += 1
p = p.next
print(tmp-1)
def append_node(self, value):
p = self.head
while p.next:
# 如果p.next, 不加next的话, 到最后一个节点,还会.next,直到None的位置
p = p.next
node = LNode(value)
p.next = node
def insert_node(self, index, value):
p = self.head
j = 0
while p and j < index:
j += 1
p = p.next
try:
node = LNode(value)
node.next = p.next
p.next = node
except Exception:
print("超出索引")
def delete_node(self, index):
p = self.head
j = 0
while p and j < index:
p = p.next
j += 1
try:
q = p.next
p.next = q.next
except Exception:
print("超出索引")
def remove_dup(self):
"""
链表去除重复值
"""
p = self.head
my_set = set()
while p.next:
my_set.add(p.next.data)
p = p.next
self.list_node(list(my_set))
def find_num(self, k):
"""
利用快慢指针, 找到链表倒数第k个位置的2数,
详见另一篇博客
:param k: 倒数第k个位置
:return:
"""
p, p_fast = self.head, self.head
i = 0
while i < k and p_fast is not None:
p_fast = p_fast.next
i += 1
if i < k:
print("超出索引")
return
while p_fast is not None:
p_fast = p_fast.next
p = p.next
print(p.data)
def reverse_node(self):
"""
链表的逆转
"""
p = self.head
p = p.next
# 这个无所谓, 这样做是为了跳过第一个空的链头
last = None
while p:
p.next, last, p = last, p, p.next
# 这个也是无所谓, 因为上面跳过了空的链头, 这样接着上面空的链头None->5->4->3->2->1->, 就是有没有空链表头的区别
self.head.next = last
def swap_node(self):
"""
链表的两两对调
1,2,3,4,5 --> None->2->1->4->3->5->
"""
p = self.head
cur = p.next
pre = p
while cur and cur.next:
next = cur.next.next
pre.next = cur.next
cur.next.next = cur
cur.next = next
pre = cur
cur = next
if __name__ == "__main__":
head = LList()
head.list_node([1, 2, 3, 4, 5])
head.swap_node()
head.print_node()
其中链表的两两对调稍微复杂些:
def swap_node(self):
"""
链表的两两对调
1,2,3,4,5 --> None->2->1->4->3->5->
"""
p = self.head
cur = p.next
pre = p
while cur and cur.next:
next = cur.next.next
pre.next = cur.next
cur.next.next = cur
cur.next = next
pre = cur
cur = next
self.head = p