-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path203. Remove Linked List Elements.py
More file actions
45 lines (33 loc) · 1.12 KB
/
203. Remove Linked List Elements.py
File metadata and controls
45 lines (33 loc) · 1.12 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
"""
https://leetcode.com/problems/remove-linked-list-elements/
Given the head of a linked list and an integer val, remove all the nodes of the linked list
that has Node.val == val, and return the new head.
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
"""
Time: O(n)
Space: O(1)
Первый элемент поначалу не трогаем, так как он может быть равен val и это может
создать сложности, которые отразится на сложности кода
"""
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if not head:
return head
tail = head
while tail.next:
current = tail.next
if current.val == val:
tail.next = current.next
else:
tail = current
return head.next if head.val == val else head