diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 3277e85e..30f5c467 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -155,23 +155,28 @@ public class Solution { class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: - """ - 根据快慢法则,走的快的一定会追上走得慢的。 - 在这道题里,有的链表短,他走完了就去走另一条链表,我们可以理解为走的快的指针。 - - 那么,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个 - 位置相遇 - """ - if headA is None or headB is None: - return None - cur_a, cur_b = headA, headB # 用两个指针代替a和b - - - while cur_a != cur_b: - cur_a = cur_a.next if cur_a else headB # 如果a走完了,那么就切换到b走 - cur_b = cur_b.next if cur_b else headA # 同理,b走完了就切换到a - - return cur_a + lenA, lenB = 0, 0 + cur = headA + while cur: # 求链表A的长度 + cur = cur.next + lenA += 1 + cur = headB + while cur: # 求链表B的长度 + cur = cur.next + lenB += 1 + curA, curB = headA, headB + if lenA > lenB: # 让curB为最长链表的头,lenB为其长度 + curA, curB = curB, curA + lenA, lenB = lenB, lenA + for _ in range(lenB - lenA): # 让curA和curB在同一起点上(末尾位置对齐) + curB = curB.next + while curA: # 遍历curA 和 curB,遇到相同则直接返回 + if curA == curB: + return curA + else: + curA = curA.next + curB = curB.next + return None ``` ### Go @@ -248,19 +253,21 @@ var getListLen = function(head) { } var getIntersectionNode = function(headA, headB) { let curA = headA,curB = headB, - lenA = getListLen(headA), - lenB = getListLen(headB); - if(lenA < lenB) { - // 下面交换变量注意加 “分号” ,两个数组交换变量在同一个作用域下时 + lenA = getListLen(headA), // 求链表A的长度 + lenB = getListLen(headB); + if(lenA < lenB) { // 让curA为最长链表的头,lenA为其长度 + + // 交换变量注意加 “分号” ,两个数组交换变量在同一个作用域下时 // 如果不加分号,下面两条代码等同于一条代码: [curA, curB] = [lenB, lenA] + [curA, curB] = [curB, curA]; [lenA, lenB] = [lenB, lenA]; } - let i = lenA - lenB; - while(i-- > 0) { + let i = lenA - lenB; // 求长度差 + while(i-- > 0) { // 让curA和curB在同一起点上(末尾位置对齐) curA = curA.next; } - while(curA && curA !== curB) { + while(curA && curA !== curB) { // 遍历curA 和 curB,遇到相同则直接返回 curA = curA.next; curB = curB.next; }