好久没写总结,今天这个题简单,但是有很多坑,所以记录一下
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
思路很简单,就是长的先走,等持平了之后一起走,判断有没有一样的。
# 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
"""
if(headA==None or headB==None):
return None
a=headA
A=headA
b=headB
B=headB
lena=1
lenb=1
while(a.next!=None):
lena+=1
a=a.next
while(b.next!=None):
lenb+=1
b=b.next
minlen=lena
if(lena!=lenb):
if(lena<lenb):
sub=temp=lenb-lena
minlen=lena
while(sub):
B=B.next
sub-=1
else:
sub=temp=lena-lenb
minlen=lenb
while(sub):
A=A.next
sub-=1
while(minlen):
if(A.val==B.val):
return A
else:
minlen-=1
A=A.next
B=B.next
return None
刚开始一直纠结python中能不能用a=headA,最后一直提示找不到next,后来发现是因为没有判断是否为空。还有lena的初值,我的判断方式,初值就应该是1,如果判断是当前节点的话,应该是0.。返回结果应该是节点,而不是节点的val。