LeetCode 160. 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 → b3
begin 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.
题目标签:Linked List
题目给了我们两个链表,让我们找到它们是否有交点,返回那个交点。
试想一下,如果是两个长度相等的链表,那么我们只需要遍历链表,比较两个点 是否 相等 就可以了。
所以,我们首先要得到两个链表的长度,如果不一样长,那么把长的链表先走,走到 和 另外一个链表一样长度的时候,开始比较两个点 是否 相等来找到交点;如果没有,那么最后就返回null。
如果两个链表有交点的话,那么从交点前一个点开始,两个链表从这里开始,之后的长度一定是相等的。
Java Solution:
Runtime beats 41.31%
完成日期:06/09/2017
关键词:singly-linked list
关键点:让更长的链表先走完多余的部分
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 { 14 public ListNode getIntersectionNode(ListNode headA, ListNode headB) 15 { 16 ListNode cursor1 = headA; 17 ListNode cursor2 = headB; 18 int len1 = getListLength(cursor1); 19 int len2 = getListLength(cursor2); 20 21 22 if(len1 > len2) 23 { 24 for(int i=0; i<len1-len2;i++) 25 cursor1 = cursor1.next; 26 } 27 else if(len1 < len2) 28 { 29 for(int i=0; i<len2-len1;i++) 30 cursor2 = cursor2.next; 31 } 32 33 while(cursor1 != null) 34 { 35 if(cursor1 == cursor2) 36 return cursor1; 37 38 cursor1 = cursor1.next; 39 cursor2 = cursor2.next; 40 } 41 42 return null; 43 } 44 45 private int getListLength(ListNode head) 46 { 47 ListNode cursor = head; 48 int len = 0; 49 50 while(cursor != null) 51 { 52 cursor = cursor.next; 53 len++; 54 } 55 56 return len; 57 } 58 }
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/