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

  • 相关阅读:
    死锁
    信号量
    实现临界区互斥的基本方法
    进程同步的基本概念:临界资源、同步和互斥
    操作系统典型调度算法
    [ 转]Collections.unmodifiableList方法的使用与场景
    【转】Android Support v4、v7、v13的区别和应用场景
    [转]finished with non-zero exit value 2
    [转]Git远程操作详解
    [转] git fetch与pull
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214763.html
Copyright © 2011-2022 走看看