题目链接
https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/
代码实现
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null)
{
return null;
}
ListNode pointA=headA;
ListNode pointB=headB;
while(pointA!=pointB)
{
pointA=pointA==null?headB:pointA.next;
pointB=pointB==null?headA:pointB.next;
}
return pointA;
}
}
c++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==NULL||headB==NULL)
{
return NULL;
}
ListNode *pointA=headA;
ListNode *pointB=headB;
while(pointA!=pointB)
{
pointA=pointA==NULL?headB:pointA->next;
pointB=pointB==NULL?headA:pointB->next;
}
return pointA;
}
};
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if headA==None or headB==None:
return None
pointA=headA
pointB=headB
while pointA != pointB:
# 指针 pointA 一开始在链表 A 上遍历,当走到链表 A 的尾部即 null 时,跳转到链表 B 上
if pointA == None:
# 指针 pointA 跳转到链表 B 上
pointA = headB
else:
# 否则的话 pointA 不断的向后移动
pointA = pointA.next
# 指针 pointB 一开始在链表 B 上遍历,当走到链表 B 的尾部即 null 时,跳转到链表 A 上
if pointB == None:
# 指针 pointA 跳转到链表 B 上
pointB = headA
else:
# 否则的话 pointB 不断的向后移动
pointB = pointB.next
# 1、此时,pointA 和 pointB 指向那个相交的节点,返回任意一个均可
# 2、此时,headA 和 headB 不相交,那么 pointA 和 pointB 均为 null,也返回任意一个均可
return pointA