/**
* 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;
int count1 = getlen(headA), count2 = getlen(headB);
ListNode *node1 = headA, *node2 = headB;
while (count1 != count2) {
if (count1 > count2) {
node1 = node1->next;
count1--;
}
else {
node2 = node2->next;
count2--;
}
}
while (node1 != NULL) {
if (node1 == node2) return node1;
node1 = node1->next;
node2 = node2->next;
}
return NULL;
}
int getlen(ListNode *pNode) {
int len = 0;
while (pNode != NULL) {
len++;
pNode = pNode->next;
}
return len;
}
};
160-相交链表
最新推荐文章于 2023-08-07 12:45:42 发布