Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
LeetCode:链接
这题的思路很巧妙,可以和LeetCode83:Remove Duplicates from Sorted List做法一样。
和val不相等的地方不用动,只需要修改和val相等的地方。
# Definition for singly-linked list.
# class ListNode(object):
# 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(-1)
dummy.next = head
pcur = dummy
while pcur.next:
'''如果和val相等 就修改连接'''
if pcur.next.val == val:
pcur.next = pcur.next.next
else:
pcur = pcur.next
return dummy.next