Bird
Raised Fist0
DSA C#programming

Stack Implementation Using Linked List in DSA C#

Choose your learning style10 modes available
Mental Model
A stack is a collection where you add and remove items only from the top, like a stack of plates. Using a linked list means each item points to the one below it, so you can easily add or remove the top item.
Analogy: Imagine a stack of books where you can only add or take the top book. Each book has a bookmark pointing to the book below it, so you always know which one is next.
Top -> [Node1] -> [Node2] -> [Node3] -> null
          ↑
        Stack top
Dry Run Walkthrough
Input: Push 10, Push 20, Push 30, Pop, Push 40
Goal: Show how the stack changes step-by-step using a linked list
Step 1: Push 10 onto empty stack
Top -> [10] -> null
       ↑
Why: First item becomes the top node
Step 2: Push 20 on top
Top -> [20] -> [10] -> null
       ↑
Why: New node points to previous top, becomes new top
Step 3: Push 30 on top
Top -> [30] -> [20] -> [10] -> null
       ↑
Why: Add new node at front, update top pointer
Step 4: Pop top item (30)
Top -> [20] -> [10] -> null
       ↑
Why: Remove top node, top moves to next node
Step 5: Push 40 on top
Top -> [40] -> [20] -> [10] -> null
       ↑
Why: Add new node at front, update top pointer
Result:
Top -> [40] -> [20] -> [10] -> null
Annotated Code
DSA C#
using System;

public class Node
{
    public int Data;
    public Node Next;

    public Node(int data)
    {
        Data = data;
        Next = null;
    }
}

public class StackLinkedList
{
    private Node top;

    public StackLinkedList()
    {
        top = null;
    }

    public void Push(int data)
    {
        Node newNode = new Node(data);
        newNode.Next = top; // new node points to current top
        top = newNode; // top updated to new node
    }

    public int Pop()
    {
        if (top == null) throw new InvalidOperationException("Stack is empty");
        int value = top.Data;
        top = top.Next; // top moves down one node
        return value;
    }

    public void PrintStack()
    {
        Node current = top;
        while (current != null)
        {
            Console.Write(current.Data + " -> ");
            current = current.Next; // move down the stack
        }
        Console.WriteLine("null");
    }
}

class Program
{
    static void Main()
    {
        StackLinkedList stack = new StackLinkedList();
        stack.Push(10);
        stack.Push(20);
        stack.Push(30);
        stack.Pop();
        stack.Push(40);
        stack.PrintStack();
    }
}
newNode.Next = top; // new node points to current top
link new node to current top to keep stack order
top = newNode; // top updated to new node
update top pointer to new node for push
if (top == null) throw new InvalidOperationException("Stack is empty");
check empty stack before pop to avoid error
top = top.Next; // top moves down one node
remove top node by moving top pointer down
current = current.Next; // move down the stack
traverse stack nodes to print all elements
OutputSuccess
40 -> 20 -> 10 -> null
Complexity Analysis
Time: O(1) for push and pop because we only add or remove the top node without traversing
Space: O(n) because each pushed item creates a new node stored in memory
vs Alternative: Compared to array-based stack, linked list avoids resizing but uses extra memory for pointers
Edge Cases
Pop from empty stack
Throws InvalidOperationException to signal no items to pop
DSA C#
if (top == null) throw new InvalidOperationException("Stack is empty");
Push on empty stack
Creates first node and sets it as top
DSA C#
newNode.Next = top; // new node points to current top
When to Use This Pattern
When you need last-in-first-out behavior with dynamic size and fast push/pop, use stack with linked list to avoid fixed size limits.
Common Mistakes
Mistake: Not updating the top pointer after push or pop
Fix: Always assign top = newNode after push and top = top.Next after pop
Mistake: Not checking for empty stack before pop
Fix: Add a check for top == null and handle empty case before popping
Summary
Implements a stack using a linked list where push and pop happen at the head.
Use when you want a stack that can grow dynamically without size limits.
The key is to always add or remove nodes at the top pointer for O(1) operations.

Practice

(1/5)
1. What is the main advantage of implementing a stack using a linked list instead of an array?
easy
A. It uses less memory than an array
B. The stack can grow dynamically without a fixed size limit
C. It allows random access to elements
D. It automatically sorts the elements

Solution

  1. Step 1: Understand stack size limitation in arrays

    Arrays have a fixed size, so stacks implemented with arrays have a maximum capacity.
  2. Step 2: Linked list dynamic size

    Linked lists can grow or shrink dynamically by adding or removing nodes, so the stack size is limited only by memory.
  3. Final Answer:

    The stack can grow dynamically without a fixed size limit -> Option B
  4. Quick Check:

    Linked list stacks grow dynamically [OK]
Hint: Linked list stacks grow dynamically, arrays do not [OK]
Common Mistakes:
  • Thinking linked list uses less memory always
  • Assuming linked list allows random access
  • Confusing stack sorting with implementation
2. Which of the following is the correct way to push an element onto a stack implemented using a linked list in C#?
easy
A. Create a new node, set its next to current top, then update top to new node
B. Create a new node, set its previous to current top, then update top to new node
C. Add the new element at the end of the linked list
D. Replace the top node's value with the new element

Solution

  1. Step 1: Understand push operation in linked list stack

    Push adds a new node at the beginning (top) of the linked list.
  2. Step 2: Correct pointer update

    The new node's next points to the current top, then top is updated to new node.
  3. Final Answer:

    Create a new node, set its next to current top, then update top to new node -> Option A
  4. Quick Check:

    Push adds node at front [OK]
Hint: Push adds node at front, update top pointer [OK]
Common Mistakes:
  • Using previous pointer instead of next
  • Adding node at end instead of front
  • Overwriting top node value instead of adding new node
3. What will be the output after the following C# code executes?
StackNode top = null;
// Push 10
StackNode node1 = new StackNode(10);
node1.next = top;
top = node1;
// Push 20
StackNode node2 = new StackNode(20);
node2.next = top;
top = node2;
// Pop
int popped = top.data;
top = top.next;
// Print top data
Console.WriteLine(top.data);
medium
A. NullReferenceException
B. 20
C. 10
D. 0

Solution

  1. Step 1: Trace push operations

    Push 10: top points to node with data 10.
    Push 20: top points to node with data 20, next points to node 10.
  2. Step 2: Trace pop operation

    Pop removes top node (20), top updated to next node (10).
  3. Step 3: Print top data

    Top now points to node with data 10, so output is 10.
  4. Final Answer:

    10 -> Option C
  5. Quick Check:

    After pop, top data = 10 [OK]
Hint: Pop removes top, next node becomes new top [OK]
Common Mistakes:
  • Printing popped value instead of new top
  • Confusing push order
  • Not updating top after pop
4. Identify the error in this pop method for a stack implemented using a linked list:
public int Pop() {
    if (top == null) {
        Console.WriteLine("Stack Underflow");
    }
    int value = top.data;
    top = top.next;
    return value;
}
medium
A. It does not return a value when stack is empty
B. It does not update the top pointer
C. It incorrectly prints "Stack Overflow" instead of "Underflow"
D. It removes the bottom node instead of the top

Solution

  1. Step 1: Check behavior when stack is empty

    If top is null, method prints message but continues to access top.data causing error or returns no value.
  2. Step 2: Missing return for empty stack case

    Method should return or throw exception when stack is empty to avoid runtime error.
  3. Final Answer:

    It does not return a value when stack is empty -> Option A
  4. Quick Check:

    Empty stack must return or throw [OK]
Hint: Always return or throw on empty stack pop [OK]
Common Mistakes:
  • Ignoring empty stack case
  • Confusing overflow with underflow
  • Not updating top pointer
5. You want to implement a method ReverseStack that reverses the elements of a stack implemented using a linked list without using extra data structures. Which approach is correct?
hard
A. Use a queue to dequeue and enqueue elements to reverse order
B. Traverse the linked list and swap data values of nodes pairwise
C. Create a new linked list and push elements from old stack to new stack
D. Use recursion to pop all elements, then push them back in reverse order

Solution

  1. Step 1: Understand constraints

    No extra data structures allowed, so using recursion (call stack) is allowed but no explicit new lists or queues.
  2. Step 2: Recursion approach

    Recursively pop all elements, then insert them back at bottom to reverse order without extra storage.
  3. Step 3: Other options use extra structures

    Swapping data or using new lists or queues violates constraints or is incorrect for stack reversal.
  4. Final Answer:

    Use recursion to pop all elements, then push them back in reverse order -> Option D
  5. Quick Check:

    Recursion reverses stack without extra structures [OK]
Hint: Use recursion to reverse stack without extra data structures [OK]
Common Mistakes:
  • Using extra linked lists or queues
  • Trying to swap node data incorrectly
  • Ignoring no extra structure constraint
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard