LeetCode 203. Remove Linked List Elements

题目

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

Example:

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

思路

Easy.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
while head and head.val == val:
head = head.next
if not head:
return head
prev, cur = head, head.next
while cur:
while cur and cur.val == val:
cur = cur.next
prev.next = cur
if cur:
prev, cur = prev.next, cur.next
return head