/**
* 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*P_A=headA;
ListNode*P_B=headB;
int count=0;//用來標記是否已經超過兩次爲空,超過即不會相交
while(count<=2)
{
if(P_A==P_B)return P_A;
P_A=P_A->next;
P_B=P_B->next;
//指向爲空了,交換鏈表遍歷
if(P_A==NULL)
{
P_A=headB;
count++;
}
if(P_B==NULL)
{
P_B=headA;
count++;
}
}
return 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) {
ListNode* A = headA, *B = headB;
while(A || B) {
if(A == B)
return A;
if(A)
A = A->next;
else
A = headB;
if(B)
B = B->next;
else
B = headA;
}
return NULL;
}
};