:type head: ListNode :type val: int :rtype: ListNode
(self, head, val)
| 6 | |
| 7 | class Solution(object): |
| 8 | def removeElements(self, head, val): |
| 9 | """ |
| 10 | :type head: ListNode |
| 11 | :type val: int |
| 12 | :rtype: ListNode |
| 13 | """ |
| 14 | # add a extra head for removing head |
| 15 | prehead = ListNode(-1) |
| 16 | prehead.next = head |
| 17 | last, pos = prehead, head |
| 18 | while pos is not None: |
| 19 | if pos.val == val: |
| 20 | last.next = pos.next |
| 21 | else: |
| 22 | last = pos |
| 23 | pos = pos.next |
| 24 | return prehead.next |
| 25 |