classSolution:defdeleteDuplication(self, p):# write code here
root = ListNode(0)
root.next= p
pre = root
while p:if p.nextand p.val == p.next.val:while p.nextand p.val == p.next.val:
p.next= p.next.next
p = p.next
pre.next= p
else:
pre = p
p = p.next
重复节点保留:单循环
# 待补充
2. 链表倒数第k个节点
快慢指针
classSolution:defFindKthToTail(self, head, k):# write code here
slow = head
fast = head
for _ inrange(k):ifnot fast:returnNone
fast = fast.nextwhile fast:
slow = slow.next
fast = fast.nextreturn slow
3. 反转链表
三指针
classSolution:# 返回ListNodedefReverseList(self, pHead):# write code here
head = pHead
if head ==Noneor head.next==None:return head
pre =Nonewhile head:
nex = head.next# 记录当前节点的下一节点
head.next= pre # 当前节点指向取反
pre = head # nex向前走一步
head = nex # head向前走一步return pre
4. 合并排序链表
classSolution:# 返回合并后列表defMerge(self, p1, p2):# write code here
cur = head = ListNode(0)# 建立helper指针while p1 and p2:if p1.val<=p2.val:
cur.next= p1
p1 = p1.nextelse:
cur.next= p2
p2 = p2.next
cur = cur.nextif p1 ==None:
cur.next= p2
elif p2 ==None:
cur.next= p1
else:
cur.next=Nonereturn head.next