Information Technology is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Stack implementation with arrays and linked lists

Stack is a Last-In-First-Out (LIFO) abstract data type; this note covers array-based and linked-list-based implementations, their invariants, complexity, C++ code examples, and exam-focused guidance.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Stacks are a simple but powerful data structure used by engineers in many parts of software and systems: function-call management (recursion), expression evaluation and conversion (infix/postfix/prefix), and backtracking algorithms. Knowing how to implement a stack with arrays and with linked lists and why to choose one over the other is essential for writing efficient code and answering exam questions on ADTs and data-structure implementations.

Key ideas

(Define terms before using them.)

  • Abstract Data Type (ADT): A specification of data and the set of operations on that data, without prescribing a particular implementation. An ADT lists allowed operations, their meanings, preconditions, and postconditions.

  • Stack: A linear ADT that stores items and allows two principal operations: push (insert an item) and pop (remove an item). A stack follows LIFO (Last-In-First-Out) order: the most recently pushed item is the first that can be popped.

  • Operations (exact statements):

    • push(x): Precondition: stack is not full (for fixed-capacity) or enough memory exists (for dynamic). Postcondition: x is now the top element. If precondition fails, operation results in overflow (array version) or allocation failure (linked list when memory cannot be obtained).
    • pop() -> x: Precondition: stack is not empty. Postcondition: removes and returns the top element x. If precondition fails, operation results in underflow.
    • peek/top() -> x: Returns the top element without removing it. Requires non-empty stack.
    • isEmpty() -> bool, isFull() -> bool (isFull applies only to fixed-capacity array implementation). For arrays: isEmpty iff top == -1; isFull iff top == N-1. For linked lists: isEmpty iff top == NULL (nullptr); isFull is not applicable except when allocation fails.
  • Invariants and common formal statements used in exams:

    • For an array stack with capacity N and integer variable top: initial state: top = -1.
    • Invariant: -1 <= top <= N-1 at all times. Number of elements stored = top + 1.
    • push(x) (array): check top < N-1; then top <- top + 1; A[top] <- x.
    • pop() (array): check top >= 0; x <- A[top]; top <- top - 1; return x.
    • For linked-list stack with pointer top (or head): initially top = NULL. push: create a new node whose next pointer points to old top; set top to new node. pop: remove top node, set top to its next, return its data.
  • Complexity claims (to state and prove briefly in exam): For both array and singly linked-list implementations, push, pop, peek, isEmpty are O(1) time (constant time) assuming memory allocation for linked list is O(1). For array implementation, space used = O(N) fixed; for linked list, space used = O(n) dynamic where n is current number of elements.

  • When to draw diagrams in an answer: draw an array of boxes indexed 0..N-1, label the index of each box and draw an arrow labeled top -> pointing to the current top index (or to an empty spot if top = -1). For linked list, draw boxes as nodes with two fields: [data | next], connect next pointers with arrows, and draw a variable named top pointing to the head node. Label NULL (or nullptr in C++) where next is null.

  • Assumptions commonly required in exam answers: array indices start at 0; integer top stores the index of current top element or -1 when empty; memory allocation succeeds for linked list unless otherwise noted.

Formulas

(For programming topics, give syntax and short complexity formulas.)

A: array used to hold elements (type depends on problem, e.g., int A[N]) — no SI unit — applies for fixed capacity stack.

top : integer index of current top element; top = -1 when stack empty — unit: index (dimensionless) — applies to array implementation.

push(x) — general operation name. Syntax to remember in C++ (array): bool push(int x) // returns false on overflow — meaning: push x if top < N-1.

int pop() // returns value or throws/indicates underflow — remove and return top element.

Time(push) = O(1), Time(pop) = O(1), Space(array) = O(N), Space(linked list) = O(n) — here n is current number of elements, N is fixed capacity.

struct Node { int data; Node* next; }; — linked-list node syntax to remember in C++.

Worked examples

(Complete C++ programs that run; each program followed by sample input and exact output.)

Example 1 — Array-based stack (fixed capacity)

C++ code:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

struct ArrayStack {
    int N;
    vector<int> A;
    int top;
    ArrayStack(int cap): N(cap), A(cap), top(-1) {}
    bool push(int x){
        if(top >= N-1) return false; // overflow
        top++;
        A[top] = x;
        return true;
    }
    bool pop(int &out){
        if(top == -1) return false; // underflow
        out = A[top];
        top--;
        return true;
    }
};

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int N; if(!(cin>>N)) return 0;
    int Q; cin>>Q;
    ArrayStack st(N);
    string cmd;
    for(int i=0;i<Q;i++){
        cin>>cmd;
        if(cmd=="push"){ int x; cin>>x; if(st.push(x)) cout<<"Pushed "<<x<<"\n"; else cout<<"Stack overflow\n"; }
        else if(cmd=="pop"){ int v; if(st.pop(v)) cout<<"Popped "<<v<<"\n"; else cout<<"Stack underflow\n"; }
    }
    return 0;
}

Sample input:

5
7
push 10
push 20
push 30
pop
push 40
pop
pop

Exact output for the sample input:

Pushed 10
Pushed 20
Pushed 30
Popped 30
Pushed 40
Popped 40
Popped 20

Example 2 — Singly linked-list stack (dynamic)

C++ code:

#include <iostream>
#include <string>
#include <new>
using namespace std;

struct Node { int data; Node* next; Node(int d): data(d), next(nullptr) {} };

struct LinkedStack {
    Node* top;
    LinkedStack(): top(nullptr) {}
    bool push(int x){
        Node* p = new (nothrow) Node(x);
        if(!p) return false; // allocation failed
        p->next = top;
        top = p;
        return true;
    }
    bool pop(int &out){
        if(!top) return false; // underflow
        Node* p = top;
        out = p->data;
        top = top->next;
        delete p;
        return true;
    }
};

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int Q; if(!(cin>>Q)) return 0;
    LinkedStack st;
    string cmd;
    for(int i=0;i<Q;i++){
        cin>>cmd;
        if(cmd=="push"){ int x; cin>>x; if(st.push(x)) cout<<"Pushed "<<x<<"\n"; else cout<<"Allocation failed\n"; }
        else if(cmd=="pop"){ int v; if(st.pop(v)) cout<<"Popped "<<v<<"\n"; else cout<<"Stack underflow\n"; }
    }
    return 0;
}

Sample input:

6
push 5
push 7
push 9
pop
pop
pop

Exact output:

Pushed 5
Pushed 7
Pushed 9
Popped 9
Popped 7
Popped 5

(These programs are minimal, exam-standard, and show clear push/pop behaviour. They do not implement peek/isFull printing but can be extended.)

Common mistakes

  • In pop: decrementing top before reading A[top] instead of after returns wrong element.
  • Mixing up index direction: some draw top increasing downward — be consistent and state your convention (index 0 at left is standard in exams).
  • For linked list: forgetting to set new node's next to old top, or forgetting to free popped node (memory leak).
  • Misstating complexity: claiming linked-list pop is O(n) — it is O(1) when removing from head.
  • Not handling allocation failure in linked list (rare in exam code, but good to mention).

For your exam

Types of questions you will see and what full-marks answers include:

  • Definitions: Define stack, LIFO, overflow, underflow. Full marks: precise one-line definitions and examples.
  • Short notes: Array vs linked-list implementation. Full marks: state code idea, time and space complexity, pros and cons (fixed capacity vs dynamic memory, locality of reference, memory overhead for pointers).
  • Derivations/proofs: Prove invariant that number of elements = top + 1 and show why push/pop preserve the invariant. Full marks: show base case (top = -1) and induction for each operation.
  • Programs: Write C/C++ code for stack using array or linked list. Full marks: correct initialization, boundary checks (overflow/underflow), correct push/pop, release memory for linked list.
  • Diagrams: Draw array boxes 0..N-1, mark top arrow; draw linked nodes [data|next] with top pointer. Full marks: clearly label top, indices, NULL, and show result after sequence of operations.

Exam tip: Always state preconditions for push/pop and mention what happens on error (return value/exception/print message) — examiners look for sound handling.

Quick check

  1. What is the initial value of top in an empty array-based stack (0-based indexing)?
  2. Time complexity of push and pop in a linked-list stack (assuming allocation O(1))?
  3. What does underflow mean for a stack?

Answers: top = -1; Time = O(1) for both push and pop; Underflow = pop attempted when stack is empty (no element to remove).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?