160. Intersection of Two Linked Lists
https://leetcode.com/problems/intersection-of-two-linked-lists/description/
Thoughts
Code
/*
* @lc app=leetcode id=160 lang=cpp
*
* [160] Intersection of Two Linked Lists
*/
// @lc code=start
/**
* 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 *cur_a = headA, *cur_b = headB;
while (cur_a != nullptr && cur_b != nullptr) {
cur_a = cur_a->next;
cur_b = cur_b->next;
}
ListNode *cur, *cur2, *flag;
if (cur_a == nullptr) {
cur = headB;
cur2 = headA;
flag = cur_b;
} else {
cur = headA;
cur2 = headB;
flag = cur_a;
}
while (flag != nullptr) {
flag = flag->next;
cur = cur->next;
}
while (cur != cur2) {
cur = cur->next;
cur2 = cur2->next;
}
return cur;
}
};
// @lc code=end
Analysis
Last updated