单链表
创建链表
# 创建链表
class Node:
# constructor
def __init__(self, x, next=None):
self.val = x
self.next = next
添加操作:先让先来的节点有所指向
#插入 第一步初始化
cur = ListNode(9)
#指向15 head的两个箭头 几个箭头就几个next
cur.next = head.next.next
head.next.next = cur
#在开头添加结点
cur = ListNode(9)
cur.next = head
head = cur
#结尾添加节点
cur = ListNode(9)
dum = head
while head.next:
head = head.next
head.next = cur
head = dum
反转链表:双指针
def ReverseList(self , head: ListNode) -> ListNode:
cur , pre = head, None
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
合并两个排序的链表:继续双指针
#双指针
class Solution:
def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
# 初始化exp的head节点
cur = dum = ListNode(0)
while pHead1 and pHead2:#两个链表指针指向害不为空时
if pHead1.val < pHead2.val:
cur.next = pHead1 #expect接上1的
pHead1 = pHead1.next #1链表指针前移
else:
cur.next = pHead2
pHead2 = pHead2.next
cur = cur.next #记得exp的指针异动
#三元组写法 if A不为空输出 A 其他输出B
cur.next = pHead1 if pHead1 else pHead2
return dum.next
链表中倒数最后k个结点:顺序查找
class Solution:
def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
#算出链表长度n
cur = pHead
n = 0
while cur:
cur = cur.next
n +=1
#输出位置为n-k的节点 要考虑k>n节点不存在
cur = pHead
if n - k < 0 :
cur = None
else:
for i in range(n-k):
cur = cur.next
return cur