(1)C语言实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode* p1 = headA;
struct ListNode* p2 = headB;
if(p1==NULL || p2 == NULL)
return NULL;
while(p1!=p2){
p1 = p1->next;
p2 = p2->next;
if(p1==p2)
return p1;
if(p1==NULL)
p1=headB;
if(p2==NULL)
p2=headA;
}
return p1;
}
(2)C++实习
/**
* 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) {
ListNode* p1 = headA;
ListNode* p2 = headB;
if(headA == NULL || headB == NULL){
return NULL;
}
while(p1!=p2){
p1 = p1->next;
p2 = p2->next;
if(p1 == p2){
return p1;
}
if(p1 == NULL){
p1 = headB;
}
if(p2 == NULL){
p2 = headA;
}
}
return p1;
}
};
(3)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) {
ListNode p1 = headA;
ListNode p2 = headB;
if(p1==null || p2==null)
return null;
while(p1!=p2){
p1 = p1.next;
p2 = p2.next;
if(p1==p2)
return p1;
if(p1==null)
p1 = headB;
if(p2 == null)
p2 = headA;
}
return p1;
}
}