203. Remove Linked List Elements
https://leetcode.com/problems/remove-linked-list-elements/
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->5Thoughts
将linked list中与val值相同的结点删除。删除val可看做在dummy后插入非val的节点。
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
dummy, cur = ListNode(), head
add = dummy
while cur:
if cur.val != val:
add.next = cur
add = add.next
cur = cur.next
add.next = None
return dummy.nextAnalysis
Errors:
node = node.next;没写在else里
时间复杂度O(n), 空间复杂度O(1)
Last updated
Was this helpful?