算法與數(shù)據(jù)結(jié)構(gòu)-鏈表

按Tags的順序來(lái)了:


  1. Remove Nth Node From End of List
移除鏈表倒數(shù)第N個(gè)node
Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

快慢指針的方法,快指針先往前走沥匈,可以自己畫(huà)個(gè)圖理解神帅,因?yàn)橐サ舻箶?shù)第N個(gè)節(jié)點(diǎn),因此慢指針要停在倒數(shù)第N+1處胳岂,因此快指針先往前走N+1步编整。
特別注意:如果快指針先走的時(shí)候就碰到了指針元素為NULL的情況,說(shuō)明要去除的節(jié)點(diǎn)是第一個(gè)節(jié)點(diǎn)乳丰,return head.next

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

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        fast = head 
        slow = head
        for i in range(n+1):
            if fast is not None:
                fast = fast.next
            else:
                return head.next
        while fast is not None:
            slow = slow.next
            fast = fast.next
        slow.next = slow.next.next
        return head
  1. Merge Two Sorted Lists
    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Merge兩個(gè)排好序的鏈表掌测,這種問(wèn)題和歸并排序差不多,代碼結(jié)構(gòu)一樣

class Solution(object):
    def mergeTwoLists(self, l1, l2):

        dummy = ListNode(0)
        a = dummy
        while l1 and l2:
            if l1.val <= l2.val:
                a.next = l1
                a = a.next
                l1 = l1.next
            else:
                a.next = l2
                a = a.next
                l2 = l2.next

        if l1:
            a.next = l1
        if l2:
            a.next = l2

        return dummy.next

  1. Reverse Linked List
    反轉(zhuǎn)單鏈表
添加一個(gè)tail節(jié)點(diǎn)产园,初始為None汞斧,new為head的下一個(gè),指針變化 head指向tail, tail和head再分別往前走一步

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        tail = None
        while head:
            new = head.next
            head.next = tail
            tail = head
            head = new 

        return tail
  1. Intersection of Two Linked Lists
    返回鏈表A,B的交點(diǎn)什燕,A,B相交之后后面的所有元素都相同粘勒。


    鏈表交點(diǎn).png
先判斷兩個(gè)列表的長(zhǎng)短,付給長(zhǎng)短兩個(gè)變量屎即,長(zhǎng)鏈表先走diff步庙睡,然后兩個(gè)一起往后走,直到一樣技俐。

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        l1 = self.length(headA)
        l2 = self.length(headB)
        diff = abs(l1 - l2)
        if l1 >= l2:
            longlist = headA
            shortlist = headB
        else:
            longlist = headB
            shortlist = headA
        
        for i in range(diff):
            longlist = longlist.next
        
        while longlist and shortlist and longlist != shortlist:
            longlist = longlist.next
            shortlist = shortlist.next
        
        return shortlist
        
    
    def length(self,head):
        if not head:
            return 0
        length = 0
        while head:
            length += 1 
            head = head.next
        
        return length

  1. Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur = head
        while cur:
            if cur.next is not None and cur.next.val == cur.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        
        return head

  1. Remove Duplicates from Sorted List II
只保留出現(xiàn)一次的元素
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy = ListNode(0)
        pre = dummy
        dummy.next = head
        while head and head.next:
            if head.val == head.next.val:
                while head and head.next and head.val == head.next.val:
                    head = head.next
                head = head.next # one more step
                pre.next = head
            else:
                pre = pre.next
                head = head.next
                
        return dummy.next
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末埃撵,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子虽另,更是在濱河造成了極大的恐慌暂刘,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,482評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件捂刺,死亡現(xiàn)場(chǎng)離奇詭異谣拣,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)族展,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,377評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)森缠,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人仪缸,你說(shuō)我怎么就攤上這事贵涵。” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,762評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵宾茂,是天一觀的道長(zhǎng)瓷马。 經(jīng)常有香客問(wèn)我,道長(zhǎng)跨晴,這世上最難降的妖魔是什么欧聘? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,273評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮端盆,結(jié)果婚禮上怀骤,老公的妹妹穿的比我還像新娘。我一直安慰自己焕妙,他們只是感情好蒋伦,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,289評(píng)論 5 373
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著焚鹊,像睡著了一般凉敲。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上寺旺,一...
    開(kāi)封第一講書(shū)人閱讀 49,046評(píng)論 1 285
  • 那天,我揣著相機(jī)與錄音势决,去河邊找鬼阻塑。 笑死,一個(gè)胖子當(dāng)著我的面吹牛果复,可吹牛的內(nèi)容都是我干的陈莽。 我是一名探鬼主播,決...
    沈念sama閱讀 38,351評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼虽抄,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼走搁!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起迈窟,我...
    開(kāi)封第一講書(shū)人閱讀 36,988評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤私植,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后车酣,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體曲稼,經(jīng)...
    沈念sama閱讀 43,476評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,948評(píng)論 2 324
  • 正文 我和宋清朗相戀三年湖员,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了贫悄。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,064評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡娘摔,死狀恐怖窄坦,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤鸭津,帶...
    沈念sama閱讀 33,712評(píng)論 4 323
  • 正文 年R本政府宣布彤侍,位于F島的核電站,受9級(jí)特大地震影響曙博,放射性物質(zhì)發(fā)生泄漏拥刻。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,261評(píng)論 3 307
  • 文/蒙蒙 一父泳、第九天 我趴在偏房一處隱蔽的房頂上張望般哼。 院中可真熱鬧,春花似錦惠窄、人聲如沸蒸眠。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,264評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)楞卡。三九已至,卻和暖如春脾歇,著一層夾襖步出監(jiān)牢的瞬間蒋腮,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,486評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工藕各, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留池摧,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,511評(píng)論 2 354
  • 正文 我出身青樓激况,卻偏偏與公主長(zhǎng)得像作彤,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子乌逐,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,802評(píng)論 2 345

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