1. 程式人生 > >【LeetCode 簡單題】53-移除連結串列元素

【LeetCode 簡單題】53-移除連結串列元素

宣告:

今天是第53道題。刪除連結串列中等於給定值 val 的所有節點。以下所有程式碼經過樓主驗證都能在LeetCode上執行成功,程式碼也是借鑑別人的,在文末會附上參考的部落格連結,如果侵犯了博主的相關權益,請聯絡我刪除

(手動比心ღ( ´・ᴗ・` ))

正文

題目:刪除連結串列中等於給定值 val 的所有節點。

示例:

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

解法1。LeetCode上的最佳做法和這個思路差不多,耗時80 ms, 在Remove Linked List Elements的Python提交中擊敗了78.10% 的使用者,程式碼如下。

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

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        dummy = ListNode(-1)
        dummy = head.next
        pre = dummy
        cur = head
        while cur:
            if cur.val == val:
                pre.next = cur.next    # 只要改變pre就可以刪除元素了,改變的方式是跳過相等的元素,將next指向下下個元素
            else:
                pre = pre.next
            cur = cur.next    # 把這句放到if-else語句中耗時降為76ms,不知為啥
        return dummy.next    # 這個地方不能return head,提交會報超時

結尾

解法1:https://blog.csdn.net/guoziqing506/article/details/51273818