[203] Remove Linked List Elements
https://leetcode.com/problems/remove-linked-list-elements/description/
- algorithms
- Easy (34.61%)
- Source Code: 203.remove-linked-list-elements.py
- Total Accepted: 217.2K
- Total Submissions: 610.6K
- Testcase Example: '[1,2,6,3,4,5,6]\n6'
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
python
# 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
"""
if not head: return None
while head and head.val == val:
head = head.next
p = head
while p and p.next:
if p.next.val == val:
p.next = p.next.next
else:
p = p.next
return head
# [1,2,2,1]