[抄题]:
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.
[暴力解法]:
时间分析:
空间分析:
[思维问题]:
节点相交不是节点相等,可见读题很重要。节点是否相等用等号即可。
[一句话思路]:
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 统计链表长度的时候,length要加,但是node不能忘了动,都要写
- 二者齐头并进之后,不需要加提前退出的corner case,就算没有也是最后才退出。应该想好
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
读懂题目很重要
[复杂度]:Time complexity: O(n) Space complexity: O(1)
还是原来的链表,缩短 扫一遍 返回,没有新建别的链表。符合就地取材原则,所以是1
[英文数据结构或算法,为什么不用别的数据结构或算法]:
两个for循环:可以直接判断
[关键模板化代码]:
//getLength public int getLength(ListNode node) { int length = 0; while(node != null) { length++; node = node.next; }
[其他解法]:
炫耀技巧,没必要
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /* * @param headA: the first list * @param headB: the second list * @return: a ListNode */ public ListNode getIntersectionNode(ListNode headA, ListNode headB) { //corner case if (headA == null || headB == null) { return null; } //keep the same length int A_len = getLength(headA); int B_len = getLength(headB); while (A_len > B_len) { headA = headA.next; A_len--; } while (A_len < B_len) { headB = headB.next; B_len--; } //find the same node while (headA != headB) { headA = headA.next; headB = headB.next; } return headA; } //getLength public int getLength(ListNode node) { int length = 0; while(node != null) { length++; node = node.next; } return length; } }