LeetCode 203 [Remove Linked List Elements]

原題

刪除鏈表中等于給定值val的所有節(jié)點。

樣例
給出鏈表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回刪除3之后的鏈表:1->2->4->5。

解題思路

  • 最基礎(chǔ)的鏈表操作,由于第一個節(jié)點可能被刪除,所以借助Dummy Node

完整代碼

# 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
        """
        if head is None:
            return head
        
        dummy = ListNode(0)
        dummy.next = head
        current = dummy
        while current.next != None:
            if current.next.val == val:
                current.next = current.next.next
            else:
                current = current.next
            
        return dummy.next
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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