剑指 Offer 52. 两个链表的第一个公共节点

方法一 双指针

遍历A,B两个链表,第一次走完当前链表时接着遍历另一个链表,这样两个链表最终会在公共节点汇合。总路程都是(b - c + a - c + c)

 1 /**
 2  * Definition for singly-linked list.
 3  * function ListNode(val) {
 4  *     this.val = val;
 5  *     this.next = null;
 6  * }
 7  */
 8 
 9 /**
10  * @param {ListNode} headA
11  * @param {ListNode} headB
12  * @return {ListNode}
13  */
14 var getIntersectionNode = function(headA, headB) {
15     let A = headA, B = headB;
16     while(A != B) {
17         A = A == null ? headB : A.next;
18         B = B == null ? headA : B.next;
19     }
20     return A;
21 };

 

方法二 哈希表

 1 /**
 2  * Definition for singly-linked list.
 3  * function ListNode(val) {
 4  *     this.val = val;
 5  *     this.next = null;
 6  * }
 7  */
 8 
 9 /**
10  * @param {ListNode} headA
11  * @param {ListNode} headB
12  * @return {ListNode}
13  */
14 var getIntersectionNode = function(headA, headB) {
15     const visited = new Set();
16     let temp = headA;
17     while (temp !== null) {
18         visited.add(temp);
19         temp = temp.next;
20     }
21     temp = headB;
22     while (temp !== null) {
23         if (visited.has(temp)) {
24             return temp;
25         }
26         temp = temp.next;
27     }
28     return null;
29 };

 

posted @ 2021-09-21 17:16  雪之下。  阅读(40)  评论(0)    收藏  举报