劍指offer詳解(鏈表)——python

3.從尾到頭打印鏈表

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回從尾部到頭部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        if not listNode:
            return []
        l=[]
        while listNode:
            l.append(listNode.val)
            listNode=listNode.next
        return l[::-1]

14.鏈表中倒數第k個結點

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        if not head or k<=0: return None
        p=q=head
        t=0
        while p and t < k: # 將兩個指針隔開k的距離
            p=p.next
            t+=1
        if t<k: return None # 若是倒數的個數大於鏈表個數則返回空
        while p!=None: # 不然將從頭的鏈表移動到已經移動的鏈表移動到結尾爲止
            q=q.next
            p=p.next
        return q

15.反轉鏈表

同時也是206. 反轉鏈表(leetcode)
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
迭代解法:python

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur, pre = head, None
        while cur:
            temp=cur.next # 保存原鏈表後續的內容,不讓鏈表斷掉。temp就是原鏈表從第二個節點開始的一個鏈表
            cur.next=pre #把cur的指針直接指向pre
            pre=cur # 替換這個改造後的pre
            cur=temp # 替換這個改造後的cur
        return pre

16.合併兩個排序的鏈表

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回合併後列表
    def Merge(self, pHead1, pHead2):
        # write code here
        if pHead1 == None:
            return pHead2
        if pHead2 == None:
            return pHead1
        cur = ListNode(0)
        # while pHead1 and pHead2:
        if pHead1.val<= pHead2.val:
            cur=pHead1
            cur.next=self.Merge(pHead1.next, pHead2)
        else :
            cur=pHead2
            cur.next=self.Merge(pHead1, pHead2.next)
        return cur

25.複雜鏈表的複製

用遞歸去作,會很簡單,但這題可能不適合pythonapp

class Solution:
    # 返回 RandomListNode
    def Clone(self, pHead):
        # write code here
        if not pHead: return None
        pCopy=RandomListNode(pHead.label) # 新建一個和pHead同樣內容的RandomListNode對象
        pCopy.random=pHead.random # 一個RandomListNode須要指定的值就是random和next
        # pCopy.next=pHead.next
        pCopy.next=self.Clone(pHead.next)
        return pCopy
相關文章
相關標籤/搜索