[LeetCode] 160. Intersection of Two Linked Lists

来源:互联网 发布:win10 蓝牙共享网络 编辑:程序博客网 时间:2024/05/18 03:07

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2                   ↘                     c1 → c2 → c3                   ↗            B:     b1 → b2 → b3

begin to intersect at node c1.

Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

问题描述:
给定两个单链表,求其相交的节点。

问题分析:
问题可以这样理解,每个给定的单链表由两部分构成,第一部分是自己独有的,第二部分是由两个链表所共享的。
为此,我们可以把第一个链表看成是x + z这样的结构,x代表独有部分的长度,z代表共有部分的长度。
类似,第二个链表看成是y + z这样的结构。
如果x == y,那么我们只需在两个链表上“齐头并进”,就必然可以找到共享的区块。
但是,如果二者的独有部分长度不一致,那么我们就可以把长的那不部分“去掉”,因为相交的区域必然不会出现在那儿。
这里的共享,是实实在在的共用一个ListNode结构,只不过有两个指针会指向该结构。

// 上述思路的直观实现class Solution {public:    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {        ListNode *p1 = headA, *p2 = headB;        if (p1 == nullptr || p2 == nullptr) return nullptr;        int lenA = 0, lenB = 0;        while (p1) {            lenA++;            p1 = p1->next;        }        while (p2) {            lenB++;            p2 = p2->next;        }        p1 = headA; p2 = headB;        while (lenA > lenB) {            p1 = p1->next;            lenA--;        }        while (lenA < lenB) {            p2 = p2->next;            lenB--;        }        while (p1 != nullptr && p2 != nullptr && p1 != p2) {            p1 = p1->next;            p2 = p2->next;        }        return p1;    }};

这里写图片描述
这里写图片描述

class Solution {public:    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {        ListNode *p1 = headA, *p2 = headB;        if (p1 == nullptr || p2 == nullptr) return nullptr;        while (p1 != nullptr && p2 != nullptr && p1 != p2) {            p1 = p1->next;            p2 = p2->next;            if (p1 == p2) return p1;            if (p1 == nullptr) p1 = headB;            if (p2 == nullptr) p2 = headA;        }        return p1;    }};

这里写图片描述
这里写图片描述

原创粉丝点击