1. 程式人生 > >兩個鏈表的交叉

兩個鏈表的交叉

ext class logs str c++ ++ write ini turn

代碼(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;
}
};

技術分享

兩個鏈表的交叉