美文网首页
160. 相交链表

160. 相交链表

作者: 衣锦昼行 | 来源:发表于2019-08-07 15:30 被阅读0次

编写一个程序,找到两个单链表相交的起始节点。
输入: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 个节点。

注意:
如果两个链表没有交点,返回 null.
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
程序尽量满足 O(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) {
        if(headA == null)
            return null;
        if(headB == null)
            return null;
       if(headA == headB)
           return headA;
        int lenA = 0,lenB = 0;
        ListNode nodeA = headA;
        ListNode nodeB = headB;
        while (nodeA != null){
            lenA++;
            nodeA = nodeA.next;
        }
        while (nodeB != null){
            lenB++;
            nodeB = nodeB.next;
        }
         nodeA = headA;
        nodeB = headB;
        if(lenA > lenB){
            int len = lenA - lenB;
            while (len>0){
                len--;
                nodeA = nodeA.next;
            }
        }
        else if(lenA < lenB){
            int len = lenB - lenA;
            while (len>0){
                len--;
                nodeB = nodeB.next;
            }
        }
        while (nodeA != null){
            if(nodeA == nodeB)
                return nodeA;
            nodeA = nodeA.next;
            nodeB = nodeB.next;
        }
        return null;
    }
}

相关文章

  • 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/hhoodctx.html