zoukankan      html  css  js  c++  java
  • 【面试题37】两个链表的第一个公共结点

    【题目描述】

    输入两个链表,找出它们的第一个公共结点。

    【解决方案】

    解法一:利用两个辅助栈,以此将两个链表的结点压入。然后分别弹出两个栈中的结点,直到找到最后一个相同的结点,即为它们的第一个公共结点。

    缺点:需要耗费O(m+n)空间复杂度;

    解法二:分别便利两个链表的长度,记录下两个链表的长度m,n (m>n),则m长的链表结点先走m-n步,直到找到它们相同的结点,即为它们的第一个公共结点。

    优点:和第一种解决方法的时间复杂度相同,但是不需要耗费空间复杂度。

    我的代码实现,仅供参考:

     1         public static ListNode FindFirstCommonNode(ListNode headA, ListNode headB)
     2         {
     3             if (headA == null || headB == null)
     4                 return null;
     5 
     6             ListNode listLong = headA, listShort = headB;
     7 
     8             int lenA = GetListLength(headA);
     9             int lenB = GetListLength(headB);
    10             int lenDif = lenA - lenB;
    11 
    12             if (lenA < lenB)
    13             {
    14                 listLong = headB;
    15                 listShort = headA;
    16                 lenDif = lenB - lenA;
    17             }
    18 
    19             //先让长链表多走m-n步
    20             while (lenDif > 0)
    21             {
    22                 listLong = listLong.Next;
    23                 lenDif--;
    24             }
    25 
    26             //两个链表一起走,直到找到相同的结点为止
    27             while ((listShort != null) && (listLong != null) && (listLong != listShort))
    28             {
    29                 listLong = listLong.Next;
    30                 listShort = listShort.Next;
    31             }
    32 
    33             return listLong;
    34         }
    35 
    36         public static int GetListLength(ListNode head)
    37         {
    38             int length = 0;
    39 
    40             while (head != null)
    41             {
    42                 head = head.Next;
    43                 length++;
    44             }
    45 
    46             return length;
    47         }
  • 相关阅读:
    GPU上的基本线性代数
    NVIDIA数据中心深度学习产品性能
    GeforceRTX系列参数对比
    NVIDIA CUDA-X AI
    NVIDIA 认证系统
    汉字手写训练和识别
    动态表单工作量给后端
    机器学习PAL数据可视化
    越是向前 越受阻力
    Caused by: java.lang.IllegalStateException: java.lang.IllegalStateException: Cannot emit more than one data
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4828195.html
Copyright © 2011-2022 走看看