首页 > 代码库 > [LeetCode]160 Intersection of Two Linked Lists
[LeetCode]160 Intersection of Two Linked Lists
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。