Implement a Stack Using a Singly Linked List

Implement stackOpsLinkedList

Implement a LIFO stackLIFOLast In, First Out — the most recently pushed element is always the first one popped. backed by a singly linked list, supporting push(v), pop(), top(), isEmpty(), and size(). Same as before, this version takes a fixed sequence of operations (each with an argument, ignored when unused) and replays them in order, returning the result of every pop, top, isEmpty, and size call as an array. A linked list is a natural fit for a stack: keep a single pointer to the "head" node, push by creating a new node that points at the old head and becomes the new one, and pop by reading the head's value and moving the pointer to whatever comes next. Every operation touches exactly one pointer near the front — nothing shifts, and nothing needs to be pre-sized or resized. That's the core advantage over an array-backed version: a stack conceptually only ever cares about its most recent element, and a linked list's head is exactly that, reachable in true O(1) regardless of how many elements came before it.

Example 1:

Input: ops = ["push","push","push","pop","pop","top"], args = [5,10,15,0,0,0]

Output: [15,10,5]

Example 2:

Input: ops = ["isEmpty","push","isEmpty","pop","isEmpty"], args = [0,7,0,0,0]

Output: [1,0,7,1]

Example 3:

Input: ops = ["push","push","size","pop","size"], args = [1,2,0,0,0]

Output: [2,2,1]

+ 5 hidden test cases run on Submit.

Constraints:

  • 1 ≤ number of operations ≤ 12
  • Each operation is one of push, pop, top, isEmpty, or size
  • 0 ≤ pushed value ≤ 1000
  • pop and top return -1 when the stack is empty
  • This version replays a fixed sequence of operations and reports the result of every pop, top, isEmpty, and size call, in order (push has no return value)

ops =

["push", "push", "push", "pop", "pop", "top"]

args =

[5, 10, 15, 0, 0, 0]