• 【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:

    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.

    提示:

    假设两个链表有合并的情况,那么合并部分的长度一定是一样的,在合并之前长度会有所不同,所以先求出长度,然后把长的链表向前走,让他们“在同一起跑线”,然后依次比较。

    代码:

    /**
     * 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;
            int lenA = 0, lenB = 0;
            ListNode *nodeA, *nodeB;
            for (nodeA = headA; nodeA; nodeA = nodeA->next, ++lenA);
            for (nodeB = headB; nodeB; nodeB = nodeB->next, ++lenB);
            if (lenB > lenA) {
                for (int i = 0; i < lenB - lenA; ++i, headB = headB->next);
            } else {
                for (int i = 0; i < lenA - lenB; ++i, headA = headA->next);
            }
            if (headA == headB) return headA;
            while (headA && headB) {
                headA = headA->next;
                headB = headB->next;
                if (headA == headB) return headA;
            }
            return NULL;
        }
    };
  • 相关阅读:
    SVN 、Git、Github的使用
    asp.net core 系列 8 Razor框架路由(下)
    asp.net core 系列 7 Razor框架路由(上)
    asp.net core 系列 6 MVC框架路由(下)
    asp.net core 系列 5 MVC框架路由(上)
    asp.net core 系列 4 注入服务的生存期
    asp.net core 系列 3 依赖注入服务
    asp.net core 系列 2 启动Startup类介绍
    asp.net core 系列 1 概述
    iframe和response.sendRedirect()跳转到父页面的问题
  • 原文地址:https://www.cnblogs.com/jdneo/p/4797408.html
Copyright © 2020-2023  润新知