Approach
Stack-based processing
For Design Skiplist, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- Push the current item with only the information later steps need.
Code notes
- 61 lines of C++ from the credited upstream file 1206.cpp.
- The implementation keeps its working state in language-native values and containers.
- 5 loop blocks detected.
Complexity
If each item is pushed and popped at most once, the stack work is linear.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Node {2 int val = -1;3 shared_ptr<Node> next;4 shared_ptr<Node> down;5};6 7class Skiplist {8 public:9 bool search(int target) {10 for (shared_ptr<Node> node = dummy; node; node = node->down) {11 advance(node, target);12 if (node->next && node->next->val == target)13 return true;14 }15 return false;16 }17 18 void add(int num) {19 20 stack<shared_ptr<Node>> nodes;21 for (shared_ptr<Node> node = dummy; node; node = node->down) {22 advance(node, num);23 nodes.push(node);24 }25 26 shared_ptr<Node> down;27 bool shouldInsert = true;28 while (shouldInsert && !nodes.empty()) {29 shared_ptr<Node> prev = nodes.top();30 nodes.pop();31 prev->next = make_shared<Node>(num, prev->next, down);32 down = prev->next;33 shouldInsert = rand() % 2 == 1;34 }35 36 37 if (shouldInsert)38 dummy = make_shared<Node>(-1, nullptr, dummy);39 }40 41 bool erase(int num) {42 bool found = false;43 for (shared_ptr<Node> node = dummy; node; node = node->down) {44 advance(node, num);45 if (node->next && node->next->val == num) {46 node->next = node->next->next;47 found = true;48 }49 }50 return found;51 }52 53 private:54 shared_ptr<Node> dummy = make_shared<Node>(-1);55 56 void advance(shared_ptr<Node>& node, int target) {57 while (node->next && node->next->val < target)58 node = node->next;59 }60};61