Skip to main content

How to Implement a Stack (LIFO) Data Structure in Batch Script

In computer science, a Stack is a data structure that follows the LIFO (Last-In, First-Out) principle. Imagine a stack of dinner plates: the last plate you put on top is the first one you take off. Stacks are essential for managing "Undo" history, navigating directories (the pushd and popd commands), and parsing complex mathematical expressions.

In this guide, we will demonstrate how to build a Stack in Batch using an indexed array and a "Pointer."

The Strategy: The Stack Pointer

To implement a stack:

  1. Initialize a top variable to 0.
  2. PUSH: To add an item, increment top and store the value at STACK_%top%.
  3. POP: To remove an item, retrieve the value at STACK_%top% and then decrement top.
note

Since Batch does not have native array or stack objects, this implementation simulates one using sequentially numbered environment variables (STACK_1, STACK_2, etc.) and a top pointer that tracks the current height of the stack.

Implementation Script

@echo off
setlocal enabledelayedexpansion

set "top=0"

echo --- STACK DEMONSTRATION (LIFO^) ---

:: 1. PUSH elements onto the stack
call :push "Apple"
call :push "Orange"
call :push "Banana"

echo.
echo Current Stack Size: !top!
call :peek
echo.

:: 2. POP elements off the stack
:pop_loop
if !top! LEQ 0 (
echo [EMPTY] No more items to pop.
goto :end
)
call :pop
echo Popped: !result!
goto :pop_loop

:end
echo.
echo --- STACK COMPLETE ---

endlocal
pause
exit /b 0

:: ============================================
:: STACK FUNCTIONS
:: ============================================

:push
:: Usage: call :push "value"
set /a "top+=1"
set "STACK_!top!=%~1"
echo Pushing: %~1
exit /b

:pop
:: Usage: call :pop (result stored in !result!)
if !top! LEQ 0 (
echo [ERROR] Stack underflow - cannot pop from an empty stack.
set "result="
exit /b 1
)
set "result=!STACK_%top%!"
set "STACK_!top!="
set /a "top-=1"
exit /b

:peek
:: Usage: call :peek (displays top element without removing it)
if !top! LEQ 0 (
echo [PEEK] Stack is empty.
exit /b 1
)
echo Top Element: !STACK_%top%!
exit /b

Why Use a Stack in Batch?

  1. Work History: If your script performs a series of complex actions (like renaming files), you can "Push" the original names onto a stack. If an error occurs, you "Pop" them off to restore everything to its original state.
  2. Recursive Navigation: When searching through subdirectories, a stack allows you to store your "Current" location while you dive into a subfolder, and then "return" exactly where you left off.
  3. Command Parsing: Stacks are used to ensure that brackets {} or parentheses () in a text file are properly balanced.

Visualizing the Process

  1. Initial: [ ] (top = 0)
  2. Push "A": [ A ] (top = 1)
  3. Push "B": [ A, B ] (top = 2)
  4. Pop: Result "B", Stack [ A ] (top = 1)

Best Practices

warning

Always check for underflow before popping. Attempting to pop from an empty stack (when top is 0) will reference an undefined variable, producing silent bugs or unexpected behavior. The :pop function in this guide includes this guard automatically.

  1. Check for Underflow: Before popping, always check if top == 0. Trying to pop from an empty stack will result in "variable not defined" errors.
  2. Pointer Naming: Use a specific prefix like S_ or STACK_ so you can identify and clear the entire stack memory if needed after processing.
  3. Peek Function: If you want to see what is on top without removing it, use the :peek function. This retrieves !STACK_%top%! without decrementing the pointer.
tip

To clear the entire stack at once, loop from 1 to !top! and unset each STACK_n variable, then reset top to 0. This prevents stale data from lingering in the environment.

Conclusion

Implementing a stack data structure adds a layer of logic and "Memory" to your scripts that standard variables cannot provide. By mastering the LIFO principle and the stack pointer methodology, you can create more resilient automation that is capable of handling complex, nested tasks and providing easy path-reversal or "Undo" capabilities.

This sophistication is what separates a linear script from a professional system management tool.