Intersection of Two Linked Lists
2017-02-24 10:50
288 查看
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
LintCode上原题,思路一致。
我最初的答案
错误点在:当输入两条不相交的链表时,将陷入死循环。
正确的代码:
这代码解决了两种情况:两链表第一个结点就相交
两链表无相交
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
LintCode上原题,思路一致。
我最初的答案
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(!headA||!headB) return NULL; ListNode *p=headA,*q=headB; while(p&&q){ if(p->next)p=p->next; else p=headB; if(q->next)q=q->next; else q=headA; if(p==q) return q; } return NULL; }
错误点在:当输入两条不相交的链表时,将陷入死循环。
正确的代码:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(!headA||!headB) return NULL; ListNode *p=headA,*q=headB; while(p&&q&&p!=q){//避免了头节点相交 p=p->next;//没加if(p->next),这样如果不相交,在if(p==q)时就会跳出去 q=q->next; if(p==q) return q; if(p==NULL) p=headB; if(q==NULL) q=headA; } return p;//不返回NULL,当两者相交时 }
这代码解决了两种情况:两链表第一个结点就相交
两链表无相交
相关文章推荐
- Intersection of Two Linked Lists(链表)
- Leetcode: Intersection of Two Linked Lists
- [leetcode160链表]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]Intersection of Two Linked Lists
- LeetCode -- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- [Leetcode 160] Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- [leetcode]Intersection of Two Linked Lists —— 熟悉python
- Intersection of Two Linked Lists
- linked-list-cycle&&find-peak-element&&intersection-of-two-linked-lists
- leetCode:Intersection of Two Linked Lists
- lintcode 中等题:Intersection of Two Linked Lists 两个链表的交叉
- 【leetcode】Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- LeetCode 160 :Intersection of Two Linked Lists