203: Remove Linked List Elements

题目要求:

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


Example:

Given:1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val= 6
Return: 1 --> 2 --> 3 --> 4 --> 5


解题思路:
  • 需要临时头节点
  • 遍历链表:while....

# Time:  O(n)
# Space: O(1)
# Definition for singly-linked list.
# class ListNode:
#     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(float("-inf"))
       dummy.next = head
       prev, curr = dummy, dummy.next
       
       while curr:
           if curr.val == val:
               prev.next = curr.next
           else:
               prev = curr
           
           curr = curr.next
       
       return dummy.next

你可能感兴趣的:(203: Remove Linked List Elements)