【面试题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         }
原文地址:https://www.cnblogs.com/HuoAA/p/4828195.html