[leetcode]Intersection of Two Linked Lists
2014-11-27 23:48
603 查看
又是个老提
先判断是否相交,如果相交,那么两个链表最后的节点是一样的。
相交那么,我们就来找相交的那个点,假设两个链表一样长,一起往后走,到相同的那个就是交点,不一样长,我们把长的切掉,然后继续这样找就好了。
先判断是否相交,如果相交,那么两个链表最后的节点是一样的。
相交那么,我们就来找相交的那个点,假设两个链表一样长,一起往后走,到相同的那个就是交点,不一样长,我们把长的切掉,然后继续这样找就好了。
/** * 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 == nullptr || headB == nullptr) return nullptr; int la = 0; int lb = 0; ListNode* tmpA = headA; ListNode* tmpB = headB; while(tmpA -> next != nullptr) { la++; tmpA = tmpA -> next; } while(tmpB -> next != nullptr) { lb++; tmpB = tmpB -> next; } if (tmpA != tmpB) return nullptr; tmpA = headA; tmpB = headB; if (lb < la) { // la must less than lb swap(tmpA, tmpB); swap(la, lb); } int diff = lb - la; for (int i = 0; i < diff; i++) { tmpB = tmpB -> next; } while (tmpA != tmpB) { tmpA = tmpA -> next; tmpB = tmpB -> next; } return tmpA; } };
相关文章推荐
- Leetcode: Intersection of Two Linked Lists
- LeetCode: Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- [leetcode]Intersection of Two Linked Lists
- [Leetcode]Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode[Linked List]: Intersection of Two Linked Lists
- [LeetCode]Intersection of Two Linked Lists
- Leetcode-Intersection of Two Linked Lists
- Intersection of Two Linked Lists--leetcode
- 【Leetcode】Intersection of Two Linked Lists in JAVA
- leetcode:Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- Leetcode: Intersection of Two Linked Lists
- 【Leetcode】:Intersection of Two Linked Lists
- 【leetcode 两个链表的交集点】Intersection of Two Linked Lists
- [LeetCode] Intersection of Two Linked Lists 两链表是否相交
- [Leetcode]Intersection of Two Linked Lists
- 和大神们学习每天一题(leetcode)-Intersection of Two Linked Lists
- Leetcode_160_Intersection of Two Linked Lists