国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

[LeetCode] Intersection of Two Linked Lists

2019-11-15 01:13:39
字體:
來源:轉載
供稿:網友
[LeetCode] 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, returnnull.
    • 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.

這道題還是先要搞懂題目問的啥。這里的intersection linked list通過看例子我們可以看出,其length可以不一樣,但是從intersect的部分開始到結束長度是一樣的,所以說多余的只會是前面的幾個值,而且一定有較長length的那個linked list多余出來的那一段的值。

所以我們首先計算兩個list的length,把較長的那個的多余的那部分的值給waive掉。這樣兩條同樣長的list就非常好找intersect的地方了。

代碼如下。~

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        int lengtha=0;        int lengthb=0;        ListNode curr1=headA;        ListNode curr2=headB;        while(curr1!=null){            lengtha++;            curr1=curr1.next;        }        while(curr2!=null){            lengthb++;            curr2=curr2.next;        }        curr1=headA;        curr2=headB;        if(lengtha>lengthb){            for(int i=0;i<lengtha-lengthb;i++){                curr1=curr1.next;            }        }else{            for(int i=0;i<lengthb-lengtha;i++){            curr2=curr2.next;            }        }        while(curr1!=curr2){            curr1=curr1.next;            curr2=curr2.next;        }        return curr1;    }}


上一篇:自定義注解

下一篇:Java線程池的那些事

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 建德市| 信宜市| 沁阳市| 海原县| 曲周县| 台北县| 盘锦市| 邳州市| 虞城县| 西乌| 兴山县| 西宁市| 枞阳县| 宁南县| 克拉玛依市| 定安县| 浦东新区| 洱源县| 台安县| 日喀则市| 浪卡子县| 来宾市| 中方县| 青神县| 济源市| 锡林浩特市| 凤凰县| 湾仔区| 罗城| 静海县| 江津市| 吉木萨尔县| 正蓝旗| 东台市| 神农架林区| 靖远县| 威远县| 广州市| 盐边县| 运城市| 沿河|