【python3】leetcode 203. Remove Linked List Elements (easy)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/86073816

203. Remove Linked List Elements (easy)

Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

先把头部为val的全过滤掉,不然pre没办法指

# 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
        """
        if not head:return []
        while(head!=None and head.val == val):head = head.next
        if not head:return []
        pre = head  #!=val
        node = head.next
        while(node):
            if node.val == val:
                pre.next = node.next
            else:
                pre = node
            node = node.next        
                
            
        return head

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/86073816