合并两个排序的链表
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
class Solution:
def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
# write code here
# 递归方法,终止条件为任一链表为空;每次递归中,将当前值较小的链表的next替换为其与另一链表的merge结果
if not pHead1:
return pHead2
if not pHead2:
return pHead1
if pHead1.val <= pHead2.val:
pHead1.next = self.Merge(pHead1.next,pHead2)
return pHead1
else:
pHead2.next = self.Merge(pHead1,pHead2.next)
return pHead2
# 普通方法,新建空链表(tips:链表为单向,可以先建空链表,再使用另一个变量指向这个空链表头,使用这个变量进行不断next操作)
# 然后依次比较两个链表头大小,添加小的,然后被添加过就往后一格
result = ListNode(None)
temp = result
while(pHead1 and pHead2):
if pHead1.val > pHead2.val:
temp.next = pHead2
pHead2 = pHead2.next
else:
temp.next = pHead1
pHead1 = pHead1.next
temp = temp.next
temp.next = pHead1 if pHead1 else pHead2
return result.next
两个链表的第一个公共结点
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
class Solution:
def FindFirstCommonNode(self , pHead1 , pHead2 ):
# write code here
# 双指针方法,将两个链表互相补充到对方的末尾,得到两个长度相同的链表,并且末尾部分依然
# 重合,这样就可以使用双指针同时依次走一步,判断是否相等
p1, p2 = pHead1, pHead2
while p1 != p2:
p1 = p1.next if p1 else pHead2
p2 = p2.next if p2 else pHead1
return p1
# 截取到相同长度,双指针方法。让长的链表先走,直到两个链表长度相同。
# 不知道为什么总是报错,说pHead2 = pHead2.next这一行 'NoneType' object has no attribute 'next'
def get_len(pHead):
num = 0
if pHead:
num += 1
pHead = pHead.next
return num
len_a, len_b = get_len(pHead1), get_len(pHead2)
while(len_a != len_b):
if len_a > len_b:
pHead1 = pHead1.next
len_a = len_a - 1
if len_a < len_b:
pHead2 = pHead2.next
len_b = len_b - 1
while pHead1 != pHead2:
pHead1 = pHead1.next
pHead2 = pHead2.next
return pHead1