zoukankan      html  css  js  c++  java
  • 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测试程序源码

  • 相关阅读:
    UVA
    剑指offer 面试题11
    SharePoint 2013+ Sqlserver 2014 Kerberos 配置传奇, 最终的解决方案 验证。
    ASC(1)G(上升时间最长的序列)
    J2EE它是一个框架?平台?规范?
    C++和python使用struct传输二进制数据结构来实现
    前端开发面试题集(二)
    C语言中<CR>是什么意思
    Delphi ParamStr 使用方法
    打包工具 使用帮助 inno setup
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214763.html
Copyright © 2011-2022 走看看