首页 > 代码库 > Leetcode: Intersection of Two Linked Lists
Leetcode: Intersection of Two Linked Lists
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 → b3begin to intersect at node c1.Notes:If the two linked lists have no intersection at all, return null.The linked lists must retain their original structure after the function returns.You may assume there are no cycles anywhere in the entire linked structure.Your code should preferably run in O(n) time and use only O(1) memory.
第一想法是用HashSet<ListNode>, A list先遍历,存HashSet,然后B list遍历,发现ListNode存在就返回。但是这个方法不满足O(1)memory的要求。
再想了一会儿,略微受了点提醒,发现可以利用这个O(n) time做文章。这个条件方便我们scan list几次都可以。于是我想到了:
先scan A list, 记录A list长度lenA, 再scan B list, 记录B list长度lenB. 看A list最后一个元素与 B list最后一个元素是否相同就可以知道是否intersect.
各自cursor回到各自list的开头,长的那个list的cursor先走|lenA - lenB|步,然后一起走,相遇的那一点就是所求
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * }10 * }11 */12 public class Solution {13 public ListNode getIntersectionNode(ListNode headA, ListNode headB) {14 if (headA==null || headB==null) return null;15 int lenA = 1;16 int lenB = 1;17 ListNode cursorA = headA;18 ListNode cursorB = headB;19 while (cursorA.next != null) {20 lenA++;21 cursorA = cursorA.next;22 }23 while (cursorB.next != null) {24 lenB++;25 cursorB = cursorB.next;26 }27 if (cursorA != cursorB) return null;28 cursorA = headA;29 cursorB = headB;30 if (lenA - lenB >= 0) {31 for (int i=0; i<lenA-lenB; i++) {32 cursorA = cursorA.next;33 }34 }35 else {36 for (int j=0; j<lenB-lenA; j++) {37 cursorB = cursorB.next;38 }39 }40 while (cursorA != cursorB) {41 cursorA = cursorA.next;42 cursorB = cursorB.next;43 }44 return cursorA;45 }46 }
Leetcode: Intersection of Two Linked Lists
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。