剑指 Offer 52. 两个链表的第一个公共节点
题解:
输入两个链表,找出它们的第一个公共节点。
示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 输出:Reference of the node with value = 8 输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
虽然给了很多条件,但实际上我们能接收的只有listA和listB。
解法:
方法一:(自写,消耗太大,拉跨)
基本思想就是双循环遍历对每一个节点都做比较
/**
执行用时:712 ms, 在所有 Java 提交中击败了5.04%的用户
内存消耗:44.1 MB, 在所有 Java 提交中击败了5.02%的用户
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode tmpA = headA;
while(tmpA != null){
ListNode tmpB = headB;
while(tmpB != null){
if (tmpA == tmpB){
return tmpA;
}
tmpB = tmpB.next;
}
tmpA = tmpA.next;
}
return null;
}
}
方法二:(官方)
本题对链表的要求很多才能真么写,感觉没什么意义
public class Solution {
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;
}
}