LeetCode 160. Intersection of Two Linked Lists
Posted randyniu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 160. Intersection of Two Linked Lists相关的知识,希望对你有一定的参考价值。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int getLen(ListNode* head) { int len = 0; while(head) { ++len; head = head->next; } return len; } ListNode *forward_long_list(int long_len, int short_len, ListNode *head) { int delta = long_len - short_len; while(head && delta) { head = head->next; --delta; } return head; } ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { int lenA = getLen(headA); int lenB = getLen(headB); if(lenA > lenB) headA = forward_long_list(lenA, lenB, headA); else headB = forward_long_list(lenB, lenA, headB); while(headA && headB) { if(headA == headB) return headA; headA = headA->next; headB = headB->next; } return NULL; } };
以上是关于LeetCode 160. Intersection of Two Linked Lists的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode:Intersection of Two Arrays
LeetCode:Intersection of Two Linked Lists
[LeetCode] Intersection of Two Arrays II
[leetcode]349.Intersection of Two Arrays