欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

203. Remove Linked List Elements

程序员文章站 2024-02-19 08:32:16
...
# 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 not head:
            return head
        if not head.next:
            if head.val == val:
                return None
            else:
                return head
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy
        p = head
        while p:
            if p.val == val:
                pre.next = p.next
                p = p.next
            else:
                pre = p
                p = p.next
        return dummy.next

有一种很天才的做法,递归法:


class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if not head:
            return None
        head.next = self.removeElements(head.next, val)
        if head.val == val:
            return head.next
        else:
            return head