• 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测试程序源码

  • 相关阅读:
    centos 安装 py 3.0+
    ubuntu下安装多版本Python
    DRF之注册器响应器分页器
    头部随着滚动高度的变化由透明慢慢变成不透明
    悬浮滚动
    判断某天是周几
    正则限制input只能输入大于0的数字
    原生js倒计时
    从两个时间段里分别计算出有几天工作日与周末
    sublime text3连续打出1到10的标签div
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214763.html
Copyright © 2020-2023  润新知