首页 > 代码库 > 两个链表的交叉

两个链表的交叉

代码(C++):

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
*/
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
// write your code here
if (headA == NULL||headB == NULL)
return NULL;
ListNode *p = headA;
ListNode *q = headB;
int a = 1, b = 1;
while (p -> next != NULL) {
p = p -> next;
a += 1;
}
while (q -> next != NULL) {
q = q->next;
b += 1;
}
if (q != p)
return NULL;
if (a > b) {
for (int i = 0; i < a-b; i++) {
headA = headA -> next;
}
} else if (a < b) {
for (int j = 0; j < b-a; j++) {
headB = headB -> next;
}
}
while (headA != headB) {
headA = headA->next;
headB = headB->next;
}
return headA;
}
};

技术分享

两个链表的交叉