-
Notifications
You must be signed in to change notification settings - Fork 0
/
2487-remove-nodes-from-linked-list.cpp
64 lines (53 loc) · 2.06 KB
/
2487-remove-nodes-from-linked-list.cpp
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Title: Remove Nodes From Linked List
// Description:
// You are given the head of a linked list.
// Remove every node which has a node with a greater value anywhere to the right side of it.
// Return the head of the modified linked list.
// Link: https://leetcode.com/problems/remove-nodes-from-linked-list/
// Time complexity: O(n)
// Space complexity: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
// helper function to reverse a list and return the new head (See: Problem 206. Reverse Linked List)
ListNode *reverseList(ListNode *head) {
ListNode *prevNode = nullptr, *nextNode;
for (ListNode *node = head; node != nullptr; prevNode = node, node = nextNode) {
// save the next node
nextNode = node->next;
// reverse the direction of the current node
node->next = prevNode;
}
// return the last node
return prevNode;
}
ListNode *removeNodes(ListNode *head) {
/* We want to achieve O(1) space complexity so we don't use stack or vector */
// reverse the list
head = reverseList(head);
// prepare an empty list with a dummy head to append
ListNode dummyHead(/* sentinel value */ INT_MIN), *dummyTail = &dummyHead;
// now we can iterate nodes from right to left
for (ListNode *node = head; node != nullptr; node = node->next) {
// append the current node to the tail only if its value is not less than the previous node
if (node->val >= dummyTail->val) dummyTail = dummyTail->next = node;
}
// cut off the tail
dummyTail->next = nullptr;
// set the new head
head = dummyHead.next;
// reverse the list back
head = reverseList(head);
// return the new head
return head;
}
};