卖萌的弱渣

I am stupid, I am hungry.

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

Solution

(Remove-Linked-List-Elements.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    # [1,1], 1
    # [1],2
    # [1],1
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if head == None:
            return head
        prev = ListNode(-1)
        prev.next = head
        cur = head
        newhead = prev

        while cur!=None:
            if cur.val == val:
                prev.next = cur.next
                cur = cur.next
                continue
            prev = prev.next
            cur = cur.next
        return newhead.next