Day 9
题目:判断两个单链表是否相交并找出交点
leetcode链接:相交链表
要点:双指针
1、Java
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
// p1指向A链表头节点,p2指向B链表头节点
ListNode p1 = headA;
ListNode p2 = headB;
while(p1 != p2){
// p1走一步,如果走到A链表末尾,则转到B链表
if(p1 == null) p1 = headB;
else p1 = p1.next;
// p2走一步,如果走到B链表末尾,则转到A链表
if(p2 == null) p2 = headA;
else p2 = p2.next;
}
return p1;
}
}
2、python
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
p1 = headA
p2 = headB
while p1 != p2:
if p1 != None:
p1 = p1.next
else:
p1 = headB
if p2 != None:
p2 = p2.next
else:
p2 = headA
return p1