【问题描述】[简单]
【解答思路】
1. 双指针法
时间复杂度:O(N^2) 空间复杂度:O(1)
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {if (headA == null || headB == null) return null;ListNode pA = headA, pB = headB;while (pA != pB) {pA = pA == null ? headB : pA.next;pB = pB == null ? headA : pB.next;}return pA;
}
2. 双链指针同时移动,确保同时到链表尾
时间复杂度:O(N+M) 空间复杂度:O(1)
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {int lengthA = getLength(headA), lengthB = getLength(headB);ListNode a = headA, b = headB;if(lengthA > lengthB){for(int i = 0; i < lengthA - lengthB; i++)a = a.next;} else {for(int i = 0; i < lengthB - lengthA; i++)b = b.next;}while(a != b){a = a.next;b = b.next;}return a;}private int getLength(ListNode head){int length = 0;for(ListNode temp = head; temp != null; temp = temp.next, length++);return length;}
【总结】
1. 链表常见思路 双指针
2. 链表问题 画图
转载链接:https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/solution/mian-shi-ti-52java-shuang-zhi-zhen-da-bai-100-by-u/
转载链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/tu-jie-xiang-jiao-lian-biao-by-user7208t/