-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMay-6-24.py
39 lines (39 loc) · 1.09 KB
/
May-6-24.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
38
39
class Solution:
# TLE
def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0)
dummy.next = head
prev,curr = dummy,head
while curr:
temp = curr.next
while temp:
if temp.val>curr.val:
prev.next = curr.next
break
temp = temp.next
if not temp:
prev = curr
curr = curr.next
return dummy.next
# Using stack
def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
stk = []
curr = head
while curr:
if stk:
while stk and stk[-1]<curr.val:
stk.pop()
stk.append(curr.val)
else:
stk.append(curr.val)
curr = curr.next
i = 1
if not stk:
return
head = ListNode(stk[0])
curr = head
while i<len(stk):
curr.next = ListNode(stk[i])
curr = curr.next
i += 1
return head