leetcode做题总结,题目Intersection of Two Linked Lists 2014/11/27
2014-12-12 04:16
429 查看
题目是两个链表在后面可能合并成一个,如果合并找出合并的点。这个题一开始我的想法是对A链每个节点中间加一个特殊节点,如果历遍B链遇到了这个特殊节点即可找到。但是这个方法有一个问题就是空间复杂度较大。所以我换了个方法将A链首尾相连,这样题目就变成了之前的链表找环形开始的节点的问题了。
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA==null||headB==null) return null; if(headA==headB) return headB; ListNode q; ListNode end; ListNode p = headA; while(p.next!=null){ p=p.next; } end=p; p=headB; while(p.next!=null){ p=p.next; } if(p!=end) return null; end.next=headA; p=headB; q=p; while(true){ p=p.next; q=q.next.next; if(p==q) break; } q=headB; while(p!=q){ p=p.next; q=q.next; } end.next=null; return q; } }
相关文章推荐
- leetcode做题总结,题目Merge Two Sorted Lists 2012/03/30
- [Leetcode题目]160. Intersection of Two Linked Lists
- leetcode做题总结,题目Merge k Sorted Lists 2012/02/13
- leetcode(160):Intersection of Two Linked Lists
- Intersection of Two Linked Lists -- leetcode
- 一道有意思的题目Intersection of Two Linked Lists(双指针)
- LeetCode160—Intersection of Two Linked Lists
- leetcode做题总结,题目Add Two Numbers /Add Binary 2011/11/01&2012/04/02
- leedcode做题总结,题目Median of Two Sorted Arrays----- 2011/03/27
- leetcode做题总结,题目Plus One 2012/04/02
- LeetCode Online Judge 题目C# 练习 - Merge Two Sorted Lists
- leetcode做题总结,题目Longest Valid Parentheses 2012/02/29
- leetcode做题总结,题目Pow(x, n)-------- 2012/03/19
- leetcode做题总结,题目Sort List 2013/11/16
- leetcode做题总结,题目Search a 2D MatrixI/II 2012/04/06
- leedcode做题总结,题目Flatten Binary Tree to Linked List 2012/10/14
- leetcode做题总结,题目Best Time to Buy and Sell Stock 2012/10/30
- leetcode做题总结,题目Remove Duplicates from Sorted ListI/II 2012/04/22
- leetcode做题总结,题目Insertion Sort List 2013/11/12
- leetcode做题总结,题目Merge Sorted Array 2012/05/20