2019-01-16

LeetCode 160. Intersection of Two Linked Lists.jpg

LeetCode 160. Intersection of Two Linked Lists

Description

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

160_statement.png

begin to intersect at node c1.

Example 1:

160_example_1.png

Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value = 8
Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.

Example 2:

160_example_2.png

Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Reference of the node with value = 2
Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [0,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.

Example 3:

Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: null
Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.

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.

描述

編寫一個(gè)程序,找到兩個(gè)單鏈表相交的起始節(jié)點(diǎn)。

思路

  • 這道題有兩種不同的寫法遥诉,其基本思路是一致的.
  • 在上面的示例中,相交的節(jié)點(diǎn)我們稱之為c奖磁,如果c點(diǎn)前面A,B鏈表的節(jié)點(diǎn)個(gè)數(shù)是相同的繁疤,那么我們從A咖为,B的起點(diǎn)同時(shí)往后走,就一定會(huì)相遇.
  • 于是我們就要想辦法把相交的節(jié)點(diǎn)前面節(jié)點(diǎn)數(shù)目變得一樣.
  • 方法一稠腊,我們分別獲取鏈表A和鏈表B的長(zhǎng)度lena和lenb躁染,我們讓其中較長(zhǎng)的鏈表先走lena-lanb步(A比B長(zhǎng),如果B更長(zhǎng)就是lenb-lena步)架忌,然后讓兩個(gè)鏈表同時(shí)往后面走.
# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-01-16 09:55:59
# @Last Modified by:   何睿
# @Last Modified time: 2019-01-16 10:10:29

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if not headA or not headB: return None
        # 獲取鏈表的長(zhǎng)度
        lena, lenb = self._lenList(headA), self._lenList(headB)
        a, b = headA, headB
        # 移動(dòng)起始位置到節(jié)點(diǎn)個(gè)數(shù)相同的第一個(gè)點(diǎn)
        if lena > lenb:
            for _ in range(lena - lenb):
                a = a.next
        elif lenb > lena:
            for _ in range(lenb - lena):
                b = b.next
        # 同時(shí)往后面走
        while a != b:
            a, b = a.next, b.next
        return a

    # 輔助函數(shù)吞彤,獲取鏈表的長(zhǎng)度
    def _lenList(self, Node):
        res = 0
        while Node:
            res += 1
            Node = Node.next
        return res
  • 方法二,為了獲得相同個(gè)數(shù)的鏈表個(gè)數(shù)的效果叹放,我們可以把鏈表A添加到鏈表B上饰恕,把鏈表B添加到鏈表B上.
  • 體現(xiàn)的形式是先從鏈表A出發(fā)的節(jié)點(diǎn)如果走完了鏈表A,就接著鏈表B開始走井仰,反過(guò)來(lái)先從鏈表B出發(fā)的鏈表也一樣.
# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-01-16 09:55:59
# @Last Modified by:   何睿
# @Last Modified time: 2019-01-16 10:10:29

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if not headA or not headB:
            return None
        a, b = headA, headB
        # 另一種寫法埋嵌,為了達(dá)到從相同個(gè)數(shù)啟起點(diǎn),我們把a(bǔ)鏈表添加到b鏈表前面
        # 把b鏈表添加到a鏈表前面
        while a != b:
            if not a:
                a = headB
            elif not b:
                b = headA
            else:
                a, b = a.next, b.next
        return a

源代碼文件在這里.
?本文首發(fā)于何睿的博客俱恶,歡迎轉(zhuǎn)載雹嗦,轉(zhuǎn)載需保留文章來(lái)源拌喉,作者信息和本聲明.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市俐银,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌端仰,老刑警劉巖捶惜,帶你破解...
    沈念sama閱讀 218,607評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異荔烧,居然都是意外死亡吱七,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門鹤竭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)踊餐,“玉大人,你說(shuō)我怎么就攤上這事臀稚×吡耄” “怎么了?”我有些...
    開封第一講書人閱讀 164,960評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵吧寺,是天一觀的道長(zhǎng)窜管。 經(jīng)常有香客問我,道長(zhǎng)稚机,這世上最難降的妖魔是什么幕帆? 我笑而不...
    開封第一講書人閱讀 58,750評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮赖条,結(jié)果婚禮上失乾,老公的妹妹穿的比我還像新娘。我一直安慰自己纬乍,他們只是感情好碱茁,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,764評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著仿贬,像睡著了一般早芭。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上诅蝶,一...
    開封第一講書人閱讀 51,604評(píng)論 1 305
  • 那天退个,我揣著相機(jī)與錄音,去河邊找鬼调炬。 笑死语盈,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的缰泡。 我是一名探鬼主播刀荒,決...
    沈念sama閱讀 40,347評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼代嗤,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了缠借?” 一聲冷哼從身側(cè)響起干毅,我...
    開封第一講書人閱讀 39,253評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎泼返,沒想到半個(gè)月后硝逢,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,702評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡绅喉,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,893評(píng)論 3 336
  • 正文 我和宋清朗相戀三年渠鸽,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片柴罐。...
    茶點(diǎn)故事閱讀 40,015評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡徽缚,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出革屠,到底是詐尸還是另有隱情凿试,我是刑警寧澤,帶...
    沈念sama閱讀 35,734評(píng)論 5 346
  • 正文 年R本政府宣布似芝,位于F島的核電站红省,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏国觉。R本人自食惡果不足惜吧恃,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,352評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望麻诀。 院中可真熱鬧痕寓,春花似錦、人聲如沸蝇闭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)呻引。三九已至礼仗,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間逻悠,已是汗流浹背元践。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留童谒,地道東北人单旁。 一個(gè)月前我還...
    沈念sama閱讀 48,216評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像饥伊,于是被迫代替她去往敵國(guó)和親象浑。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蔫饰,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,969評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,332評(píng)論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,509評(píng)論 0 23
  • 第三怪,讓人呆愉豺, 巴士站牌一小塊篓吁。 不寫車號(hào)和站名, 若未坐過(guò)靠瞎猜蚪拦。
    珠江潮平閱讀 218評(píng)論 22 14
  • 任何一件事杖剪,開始往往比較困難,因?yàn)槿f(wàn)事開頭難外盯,開始,什么也不清楚翼雀,也沒什么經(jīng)驗(yàn)饱苟,所以事情辦的比較費(fèi)勁。 其次呢狼渊,第...
    暴走的大兵閱讀 137評(píng)論 0 0
  • 地球上為什么會(huì)有各種各樣的生物箱熬?新物種如何出現(xiàn)的,舊物種又是怎么消失狈邑?生命形態(tài)為什么會(huì)隨著時(shí)間變化城须? 關(guān)鍵詞:變異...
    狩獵書生閱讀 885評(píng)論 0 0