Leetcode#160 Intersection of Two Linked Lists
2015-02-02 18:22
127 查看
原题地址
先将A链末尾和B链头部接起来
然后判断是否有环,如果无环,说明肯定不想交,如果有环,那么相交的位置就是环开始的位置
第一遍做的时候没遇到什么问题,第二遍做的时候各种出错,后来发现原来在用快慢指针法的时候快慢指针要从起点开始,否则计算出来的第一个相交位置不是环开始的位置。。
代码:
先将A链末尾和B链头部接起来
然后判断是否有环,如果无环,说明肯定不想交,如果有环,那么相交的位置就是环开始的位置
第一遍做的时候没遇到什么问题,第二遍做的时候各种出错,后来发现原来在用快慢指针法的时候快慢指针要从起点开始,否则计算出来的第一个相交位置不是环开始的位置。。
代码:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if (!headA || !headB) return NULL; ListNode *h = headA; while (h->next) h = h->next; h->next = headB; ListNode *fast = headA; ListNode *slow = headA; bool running = false; ListNode *res = NULL; while ((!running || fast != slow) && fast && fast->next) { running = true; fast = fast->next->next; slow = slow->next; } if (fast == slow) { res = headA; while (res != slow) { res = res->next; slow = slow->next; } } h->next = NULL; return res; }
相关文章推荐
- LeetCode#160 Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- [leetcode]Intersection of Two Linked Lists寻找两链表的公共节点
- Intersection of Two Linked Lists
- LeetCode.160 Intersection of Two Linked Lists
- LeetCode Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- LeetCode[Linked List]: Intersection of Two Linked Lists
- Leetcode_160_Intersection of Two Linked Lists
- Intersection of Two Linked Lists (求两个单链表的相交结点)
- Leetcode: Intersection of Two Linked Lists
- leetcode-Intersection of Two Linked Lists-160
- Intersection of Two Linked Lists
- leetcode:Intersection of Two Linked Lists(两个链表的交叉点)
- leetcode 日经贴,Cpp code -Intersection of Two Linked Lists
- LeetCode Compare Version Numbers, Maximum Gap, Find Peak Element, Intersection of Two Linked Lists
- leetcode Intersection of Two Linked Lists
- [LeetCode] Intersection of Two Linked Lists 题解
- LeetCode 160 Intersection of Two Linked Lists
- 【LeetCode-面试算法经典-Java实现】【160-Intersection of Two Linked Lists(单链表的交集)】