The stack is useful. In Python, collection.deque
can make faster stack than normal list.
https://leetcode.com/problems/remove-nodes-from-linked-list/
https://docs.python.org/3/library/collections.html
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
st = deque()
n = head
while n:
if not st:
st.append(n)
n = n.next
continue
p = st.pop()
if n.val <= p.val:
st.append(p)
st.append(n)
n = n.next
continue
n = None
while st:
p = st.pop()
p.next = n
n = p
return n