码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]160 Intersection of Two Linked Lists

时间:2015-01-09 19:34:00      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problemset/algorithms/

http://www.cnblogs.com/yuzhangcmu/p/4128794.html


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
    // Assume headA and headB not null.
    
    public ListNode getIntersectionNode(ListNode headA, ListNode headB)
    {
        // Solution A:
        return getIntersectionNode_TwoPointer(headA, headB);
        
        // Solution B:
        // return getIntersectionNode_BuildPath(headA, headB);
    }
    
    ///////////////////////////
    // Solution A: TwoPointer
    // 
    public ListNode getIntersectionNode_TwoPointer(ListNode headA, ListNode headB)
    {
        ListNode a = headA;
        ListNode b = headB;
        while (a != b)
        {
            if (a == null)
                a = headB;
            else
                a = a.next;
            
            if (b == null)
                b = headA;
            else
                b = b.next;
        }
        return a;
    }

    ///////////////////////////
    // Solution B: BuildPath
    // 
    private ListNode getIntersectionNode_BuildPath(ListNode headA, ListNode headB) 
    {
        List<ListNode> pathA = buildPath(headA);
        List<ListNode> pathB = buildPath(headB);
        
        // Check
        int iA = pathA.size() - 1;
        int iB = pathB.size() - 1;
        
        ListNode toReturn = null;
        while (iA >= 0 && iB >= 0)
        {
            if (pathA.get(iA) == pathB.get(iB))
            {
                toReturn = pathA.get(iA);
                iA --;
                iB --;
            }
            else
            {
                break;
            }
        }
        return toReturn;
    }
    
    private List<ListNode> buildPath(ListNode head)
    {
        List<ListNode> toReturn = new ArrayList<>();
        while (head != null)
        {
            toReturn.add(head);
            head = head.next;
        }
        return toReturn;
    }
}


[LeetCode]160 Intersection of Two Linked Lists

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1601279

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!