标签: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