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
思路
简单的链表删除操作。
一定要搞清楚边界条件:如果删除第一个或者最后一个元素会怎么样。然后问题就迎刃而解了。
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
| class Solution(object): def removeElements(self, head, val): """ :type head: ListNode :type val: int :rtype: ListNode """ if (head): cur = head while (cur): if (cur.val == val): if (cur.next): head = cur.next else: head = None cur = head else: break if (cur): while (cur.next is not None): if (cur.next.val == val): cur.next = cur.next.next else: cur = cur.next return head
|