Article directory
topic
Give you the head node head of a linked list.
Remove every node with a larger value to the right.
Returns the head node head of the modified linked list.
Example 1:
Input: head = [5,2,13,3,8]
Output: [13,8]
Explanation: The nodes that need to be removed are 5, 2 and 3.
- Node 13 is to the right of node 5.
- Node 13 is to the right of node 2.
- Node 8 is to the right of node 3.
Example 2:
Input: head = [1,1,1,1]
Output: [1,1,1,1]
Explanation: The value of each node is 1, so there are no nodes that need to be removed.
hint:
The number of nodes in the given list is in the range [1, 105]
1 <= Node.val <= 105
Problem: 2487. Remove node from linked list
Ideas
Use a monotonic stack, retain an array that monotonically decreases from left to right, and assign values to nodes.
When constructing a monotonic stack, we maintain a non-increasing array
. If we find that the next node is larger than the top element of the stack, we will keep popping the top element of the stack until the stack is Empty, or the top element of the stack is greater than the next node
the complexity
time complexity:
O ( n ) O(n)O ( n )
Space complexity:
Addition O ( n ) O(n)O ( n )
Code
# 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]:
stack = []
index = head
while index!=None:
while stack!=[] and stack[-1]<index.val:
stack.pop()
stack.append(index.val)
index = index.next
index = head
for i in range(len(stack)):
index.val = stack[i]
if i!=len(stack)-1:
index = index.next
if index!=None : index.next = None
return head