LeetCode (160) Intersection of Two Linked Lists

题目

Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
题目
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.

分析

给定两个链表,求它们的交叉节点。

要求,时间复杂度在O(n)内,空间复杂度为O(1)

两个链表的长度不定,但是交叉节点的后续节点全部相同,所以先求得每个链表的长度lenAlenB,将较长的链表先移动|lenAlenB|个位置,然后同时后移,遇到的第一个值相等的节点既是要求的交叉节点。

AC代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (!headA || !headB)
            return NULL;

        ListNode *p = headA, *q = headB;

        //求出输入两个链表的长度
        int lenA = 0, lenB = 0;
        while (p)
        {
            ++lenA;
            p = p->next;
        }//while

        while (q)
        {
            ++lenB;
            q = q->next;
        }//while

        //让长的链表先移动多出的节点
        p = headA;
        q = headB;
        if (lenA > lenB)
        {
            int i = 0;
            while (p && i < lenA - lenB)
            {
                p = p->next;
                ++i;
            }//while
        }
        else{
            int j = 0;
            while (q && j < lenB - lenA)
            {
                q = q->next;
                ++j;
            }//while
        }

        while (p && q && p->val != q->val)
        {
            p = p->next;
            q = q->next;
        }//while

        return p;
    }
};

GitHub测试程序源码

原文地址:https://www.cnblogs.com/shine-yr/p/5214763.html