-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23. RemoveLinkedListElement.py
37 lines (28 loc) · 1.12 KB
/
23. RemoveLinkedListElement.py
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
#PS: https://leetcode.com/problems/remove-linked-list-elements
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
if not head:
return
else:
cur = head
prev = None
while(cur):
while(prev == None and cur.val == val): #If first element = val and are repeated multiple times.
cur = cur.next
head = cur
if(cur == None):
return cur
while(cur.val == val and prev != None): #If its not a first element and are not repeated multiple times.
cur = cur.next
prev.next = cur
if(cur == None):
return head
#Moving ahead if element doesn't match
prev = cur
cur = cur.next
return head