思路
两个链表相交 则链表的末尾必定会相等 链表从后往前遍历,最后一个相等结点即为相交的第一个结点
可用栈来处理(先进后出)
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
s=[]
t= []
ans = None
while headA:
s.append(headA)
headA=headA.next
while headB:
t.append(headB)
headB=headB.next
i = len(s)-1
j = len(t)-1
while i>=0 and j>=0 and s[i]==t[j]:
ans=s[i]
i-=1
j-=1
return ans
另一种解法:
先获取两个链表的长度,较长的先编辑,直到此时两个链表长度相等,此时开始比较结点是否相等
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
#获取两个链表长度
headAlen = 0
headBlen = 0
A = headA
B =headB
while A:
headAlen+=1
A=A.next
while B:
headBlen+=1
B=B.next
A,B =headA,headB
if headAlen>headBlen:
for i in range(headAlen-headBlen):
A=A.next
elif headBlen>headAlen:
for i in range(headBlen-headAlen):
B=B.next
while A and B:
if A==B:
return A
A=A.next
B=B.next
return None
PS:
1.遍历不可用head来进行 如链表:[4,5,6] ,遍历链表后,此时 head=6,而不是再回到4
本题在比较结点的时候不要用.next来比较 有一种情况 :两个链表都相等 (链表结点:结点地址)
None即列表为空 []
1.