美文网首页
160. 相交链表

160. 相交链表

作者: justonemoretry | 来源:发表于2021-09-02 21:34 被阅读0次
image.png

解法

自己想的算法,整体时间复杂度为o(m+n),空间复杂度为o(1)。找出长度的差值,让两个链表能一起到终点

/**
 * 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) {
        // 找出两个链表相差的长度,以相同的长度位置向后遍历
        int len1 = 0;
        int len2 = 0;
        ListNode temp = headA;
        while (temp != null) {
            len1++;
            temp = temp.next;
        }

        temp = headB;
        while (temp != null) {
            len2++;
            temp = temp.next;
        }

        if (len1 >= len2) {
            int diff = len1 - len2;
            while (diff > 0) {
                headA = headA.next;
                diff--;
            }
        } else {
            int diff = len2 - len1;
            while (diff > 0) {
                headB = headB.next;
                diff--;
            }
        }
        
        while (headA != null) {
            if (headA == headB) {
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
        }
        return null;
    }
}

下面这个是官方解法,比较巧妙,利用不相等的长度,走完自己再走对方链表,找到两者相交的点。


image.png
/**
 * 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 tempA = headA;
        ListNode tempB = headB;
        while (tempA != tempB) {
            tempA = tempA == null ? headB : tempA.next;
            tempB = tempB == null ? headA : tempB.next;
        }
        return tempA;
    }
}

相关文章

  • 160. 相交链表

    160. 相交链表[https://leetcode.cn/problems/intersection-of-tw...

  • TOP 100 51 - 56

    160. 相交链表[https://leetcode-cn.com/problems/intersection-o...

  • 160. 相交链表

    160. 相交链表[https://leetcode-cn.com/problems/intersection-o...

  • LeetCode 156-160

    160. 相交链表[https://leetcode-cn.com/problems/intersection-o...

  • LeetCode 160. 相交链表

    160. 相交链表 编写一个程序,找到两个单链表相交的起始节点。 示例 1: 输入:intersectVal = ...

  • leetcode的题目160

    160. 相交链表 编写一个程序,找到两个单链表相交的起始节点。 例如,下面的两个链表: 在节点 c1 开始相交。...

  • 每周 ARTS 第 6 期

    1. Algorithm 160. 相交链表(简单) 描述: 编写一个程序,找到两个单链表相交的起始节点。 示例:...

  • 160. 相交链表

    160. 相交链表 编写一个程序,找到两个单链表相交的起始节点。 如下面的两个链表: 在节点 c1 开始相交。 示...

  • LeetCode刷题分类之双指针160. 相交链表

    160. 相交链表 题目 编写一个程序,找到两个单链表相交的起始节点。 如下面的两个链表: 在节点 c1 开始相交...

  • 【LeetCode】链表专题

    160.相交链表 返回两个链表相交的节点 19.删除链表的倒数第N个节点 返回链表的头结点。 21.合并两个有序链表

网友评论

      本文标题:160. 相交链表

      本文链接:https://www.haomeiwen.com/subject/uhebiltx.html