Editor with Undoable List Changes
You are required to implement a data structure that maintains an initially empty Singly Linked List alongside an Undo Stack. This allows you to track and reverse successful operations.
You must implement a class UndoLinkedList with the following operations:
- insertNode(i, x): Inserts a new node with value x at index i (0-indexed). Valid positions are 0 through count.
- If the position is out of bounds, return "INVALID" and do not record the action in the history.
- If successful, return an empty string "" and push the action to the undo stack.
- deleteNode(i): Deletes the data node at index i. Valid positions are 0 through count - 1.
- If the position is out of bounds, return "INVALID" and do not record the action in the history.
- If successful, return an empty string "". You must store the deleted value and index in the undo stack so the node can be perfectly restored later.
- undo(): Reverses the latest successful insertNode or deleteNode operation.
- If the undo stack is empty, return "EMPTY HISTORY".
- If successful, return an empty string "". Note: The undo operation itself does not create a new history record.
- printList(): Return a string containing the data sequence space-separated (e.g., "10 20 30"). If the list is empty, return an empty string "" (which will result in a blank line being printed).
- getList(): Return a vector<int> containing the current sequence of data node values.
Example 1:
Input: ops = [["UndoLinkedList"], ["INSERT", "0", "10"], ["INSERT", "1", "20"], ["PRINT"], ["UNDO"], ["PRINT"]]
Output: [null, null, null, "10 20", null, "10"]
Explanation:
- 10 and 20 are inserted successfully.
- The first PRINT shows (10 20).
- UNDO pops the last action (inserting 20) and reverses it by deleting the node at index 1.
- The final PRINT shows (10).
Example 2:
Input: ops = [["UndoLinkedList"], ["UNDO"], ["INSERT", "5", "99"], ["UNDO"]]
Output: [null, "EMPTY HISTORY", "INVALID", "EMPTY HISTORY"]
Explanation:
- The first UNDO fails because the stack is empty.
- INSERT 5 99 fails because the index is out of bounds, so it does not add to the history.
- The final UNDO still fails because the invalid insert did not push anything to the stack.
Now Your Turn!
Pick the correct output for the given inputInput: ops = [["UndoLinkedList"], ["INSERT", "0", "5"], ["DELETE", "0"], ["PRINT"], ["UNDO"], ["PRINT"]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= Number of Queries <= 104
- -104 <= i <= 104
- -109 <= x <= 109
Note : negative indices will always produce INVALID output