Linked List Add and Remove Operations
Problem statement
Implement a singly linked list of integers. It starts empty, and positions are counted from 0 at the head. It supports four operations:
"addFirst v": add a node with valuevat the head."addLast v": add a node with valuevat the tail."addAt i v": add a node with valuevso that it ends up at positioni. The node that was at positioni, if any, and everything after it move back by one. Ifiequals the current size, the node goes at the tail."removeAt i": remove the node at positioni.
You get the operations in order as the string array operations. Run them all and return the values of the final list from head to tail (an empty array if the list is empty).
Function
applyListOperations(operations: String[]) → int[]Examples
Example 1
operations = ["addLast 4","addFirst 9","addAt 1 7","addLast 2","removeAt 0"]return = [7,4,2]The list changes like this: [4], then [9, 4], then [9, 7, 4] (7 goes in at index 1), then [9, 7, 4, 2], and removing index 0 leaves [7, 4, 2].
Example 2
operations = ["addAt 0 5","addAt 1 -3","addAt 1 0"]return = [5,0,-3]addAt 0 5 on an empty list gives [5]. addAt 1 -3 adds at the end, giving [5, -3]. addAt 1 0 puts 0 before the old index-1 node: [5, 0, -3].
Example 3
operations = ["addFirst 1","removeAt 0"]return = []The only node is removed, so the list ends empty.
Constraints
1 <= operations.length <= 1000- Each operation has one of the four forms above, with single spaces and integers written in plain decimal.
- Every value
vsatisfies-1000 <= v <= 1000. - Every index is valid when its operation runs:
0 <= i <= sizeforaddAtand0 <= i < sizeforremoveAt.