【Leetcode鏈表】移除鏈表元素(203)

題目

刪除鏈表中等於給定值 val 的全部節點。指針

示例:code

輸入: 1->2->6->3->4->5->6, val = 6
輸出: 1->2->3->4->5

解答

三種方法:遞歸

  • 雙指針
  • 遞歸
  • 新開闢一個鏈表,增長空間複雜度

經過代碼以下:rem

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

class Solution:
    # # 方法一:雙指針。 時間複雜度O(n),空間複雜度O(1)
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        thead = ListNode(-100)
        thead.next = head
        p, c = thead, head

        while c:
            if c.val == val:
                p.next = c.next
                c = c.next
            else:
                p = c
                c = c.next
        return thead.next

    # # 方法三:
    # # 最笨方法,新建一條鏈表存。時間複雜度O(n),空間複雜度O(n)
    # def removeElements(self, head: ListNode, val: int) -> ListNode:
    #     thead = ListNode(-100)
    #     p = thead
    #     while head:
    #         if head.val != val:
    #             temp = ListNode(head.val)
    #             p.next = temp
    #             p = temp
    #         head = head.next
    #     return thead.next


    # # 方法二:遞歸
    # # 回溯時,判斷當前節點的值是否是val。 時間複雜度O(n),空間複雜度O(n)
    # def removeElements(self, head: ListNode, val: int) -> ListNode:
    #     if not head:
    #         return head
        
    #     head.next = self.removeElements(head.next, val)
    #     if head.val == val:
    #         return head.next
    #     return head
相關文章
相關標籤/搜索