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:

    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.

    题目要求:

    求两个链表的交点,如果没有,则返回NULL

    要求O(n)的时间复杂度和O(1)的空间复杂度

    解题思路:

    1、如果不考虑空间复杂度,可以用set容器记录第一个链表的所有结点,依次遍历第二个链表,第一个存在set中的结点即为交点,否则不存在。

    2、第一个链表长为x,第二个链表长为y,假设x>y,让第一个链表指针先走x-y步,(这样两个链表指针就长度对齐),然后两个链表指针一起走,如果遇到对应相等,则为交点,否则不存在。

    代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        int getLength(ListNode *head){
            int i=0;
            for(ListNode *p=head;p!=NULL;p=p->next)
                i++;
            return i;
        }
        
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            if(headA==NULL || headB==NULL) return NULL;
            int lenA=0,lenB=0;
            ListNode *pA,*pB;
            pA=headA;
            pB=headB;
            
            lenA=getLength(pA);
            lenB=getLength(pB);
            
            if(lenA>lenB){
                for(int i=lenA-lenB;i>0;i--)
                    pA=pA->next;
            }
            
            if(lenB>lenA){
                for(int i=lenB-lenA;i>0;i--)
                    pB=pB->next;
            }
            
            while(pA!=pB){
                pA=pA->next;
                pB=pB->next;
            }
            
            if(pA==pB) 
                return pA;
            else 
                return NULL;
        }
    };
  • 相关阅读:
    2018年11月1日开通博客园感想!
    Aspnet MVC 异步调用
    AspNet WebApi : MessageHandler(消息处理器 )
    AspNet MVC : 操作/控制器过滤器(action filter)
    PHP 面向对对象基础(接口,类)
    原生Ajax + Promise
    基于Qt QGraphicsView的多点触摸绘图
    node应用通过multer模块实现文件上传
    AspNet WebApi: 了解下HttpControllerDispatcher,控制器的创建和执行
    视频投影(二维视频投影到三维模型上)
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4464041.html
Copyright © 2011-2022 走看看