1. 程式人生 > >leetcode203 移除連結串列元素 --python

leetcode203 移除連結串列元素 --python

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

示例:

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

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

class Solution:
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        res = []
        while head:
            if head.val != val:
                res.append(head.val)
            head = head.next
        return res            

提交結果:
在這裡插入圖片描述