3 Linear Data Structures Stacks And Queues

Data Structures and Algorithms · Unit 3

Linear Data Structures: Stacks and Queues

Exam-focused notes for Linear Data Structures: Stacks and Queues (Data Structures and Algorithms, BIT201): what the TU syllabus asks and how it has actually been tested, with 12 solved past questions from this unit.

Linear Data Structures: Stacks and Queues in short

Stacks and queues are linear structures that restrict where we add and remove items. They are used in expression evaluation, function calls, scheduling and many other tasks.

Linear Data Structures: Stacks and Queues: notes

Stack definition and operations

A stack is a linear structure in which insertion and deletion happen at one end only, called the top. It follows LIFO (Last In, First Out): the last item pushed is the first item popped. A pile of plates is a good example.

Main operations:

  • push(x): add x on the top. If the stack is full, this is overflow.
  • pop(): remove and return the top item. If the stack is empty, this is underflow.
  • peek() or top(): read the top item without removing it.
  • isEmpty() and isFull(): check the state.

Array implementation in C:

#define MAX 5
int stack[MAX], top = -1;

void push(int x) {
    if (top == MAX - 1) { printf("Overflow\n"); return; }
    stack[++top] = x;
}
int pop() {
    if (top == -1) { printf("Underflow\n"); return -1; }
    return stack[top--];
}

If we push 10, 20, 30, then top is 2. A pop returns 30 and top becomes 1. All operations take $O(1)$ time.

Uses of stack: function calls, undo operations, bracket matching, expression conversion and evaluation, and depth first search.

Queue definition and operations

A queue is a linear structure in which insertion happens at one end, the rear, and deletion at the other end, the front. It follows FIFO (First In, First Out). A line of people at a ticket counter is a good example.

Main operations:

  • enqueue(x): add x at the rear. A full queue gives overflow.
  • dequeue(): remove the item at the front. An empty queue gives underflow.
  • peek(): read the front item.
  • isEmpty() and isFull().

Differentiation between stack and queue

StackQueue
Follows LIFOFollows FIFO
Insert and delete at the same end (top)Insert at rear, delete at front
One pointer: topTwo pointers: front and rear
Operations are push and popOperations are enqueue and dequeue
Used in recursion, undo, expression evaluationUsed in scheduling, buffering, BFS
Last inserted item is removed firstFirst inserted item is removed first

Simple queue implementation

In an array-based simple (linear) queue, front and rear start at -1.

#define MAX 5
int q[MAX], front = -1, rear = -1;

void enqueue(int x) {
    if (rear == MAX - 1) { printf("Overflow\n"); return; }
    if (front == -1) front = 0;
    q[++rear] = x;
}
int dequeue() {
    if (front == -1 || front > rear) { printf("Underflow\n"); return -1; }
    return q[front++];
}

Its weakness is wasted space. Suppose MAX is 5. We enqueue 10, 20, 30, 40, 50 and then dequeue twice. Now front is 2 and rear is 4. The two freed slots at the start cannot be reused, so the queue reports overflow even though it has free space. The circular queue solves this.

What this unit covers

  • Stack definition and operations
  • Queue definition and operations
  • Differentiation between stack and queue
  • Simple queue implementation
  • Circular queue advantages and implementation
  • Priority queue definition and implementation
  • Queue implementation using linked list
  • Stack implementation using linked list
  • Infix to postfix conversion using stack
  • Postfix expression evaluation algorithm

Circular queue advantages and implementation

2082 · 5 marks

Why do we need circular queue? Explain. [5]

In a simple linear queue implemented using an array, two pointers are maintained: - Front - points to the first element - Rear - points to the last element Consider a queue of size 5: After Enqueue A, B, C, D, E and then Dequeue A, B: Now if we try to Enqueue F, the condition Rear == MAX - 1 is T...

Open this answer on its own page →

2080 · 5 marks

What is circular queue? How can you implement circular queue? [5]

A circular queue is a linear data structure that follows the FIFO (First In First Out) principle, but the last position is connected back to the first position to form a circle. It overcomes the major limitation of a simple (linear) queue where memory space is wasted after deletions, even though ...

Open this answer on its own page →

0 · 5 marks

Why circular queue is advantageous over linear queue? Write algorithm for enqueue and is full operation for circular queue. [5]

In a linear queue, once the rear pointer reaches the last index of the array, no more elements can be inserted even if there are empty slots at the front (created after dequeue operations). This leads to wastage of memory space. A circular queue solves this problem by treating the array as a circ...

Open this answer on its own page →

Infix to postfix conversion using stack

2082 · 5 marks

Convert the infix expression 7 * 8 + 10 - 2 to postfix using stack. [5]

Show solved answer

Given Data

Infix expression to convert: $$7 * 8 + 10 - 2$$

Operator precedence:

  • *, / : higher
  • +, - : lower

Associativity: left to right.


Conversion Rules (Stack Method)

  1. Scan tokens left to right.
  2. Operand → append to output.
  3. Operator → pop operators from stack with precedence greater than or equal to the current one (for left-associative operators), append them to output, then push the current operator.
  4. End → pop all remaining operators to output.

Step-by-Step Trace

StepTokenActionStack (bottom→top)Output
17operand → output(empty)7
2*push*7
38operand → output*7 8
4+* ≥ + so pop *; push ++7 8 *
510operand → output+7 8 * 10
6-+ ≥ - so pop +; push --7 8 * 10 +
72operand → output-7 8 * 10 + 2
8Endpop -(empty)7 8 * 10 + 2 -

Verification (evaluate postfix)

Given values: $7,8,+,*$ etc. Compute $7 \times 8 = 56$; $56 + 10 = 66$; $66 - 2 = 64$. Infix: $7 \times 8 + 10 - 2 = 56 + 10 - 2 = 64$. ✓ Matches.


Result

$$\boxed{7\ 8\ *\ 10\ +\ 2\ -}$$

Open this answer on its own page →

2078 · 10 marks

Explain algorithm to convert an infix expression to postfix using stack? Use this algorithm to convert (A+B)*C-D to postfix.[10]

  • Infix expression to convert: $(A+B)C-D$ - Data structure to use: Stack - Task: (a) explain the algorithm, (b) apply it to the given expression. All required data is present. --- Operator Precedence --------------------- ^ 3 (highest) , / 2 +, - 1 ( inside stack 0 (lowest) --- Step Symbol Stack ...
Open this answer on its own page →

Simple queue implementation

2082 · 5 marks

What is simple queue? Describe about any three types of graphs. [2+3]

Show solved answer

Simple Queue and Types of Graphs


Simple Queue [2 marks]

A simple queue (also called a linear queue) is a linear data structure that follows the FIFO (First In First Out) principle, meaning the element inserted first is the element removed first.

Key characteristics:

  • Elements are inserted from the REAR end
  • Elements are deleted from the FRONT end
  • Once the rear reaches the maximum size, no more insertions are possible (even if space exists at the front after deletions)
FRONT                        REAR
  |                            |
  v                            v
[ 10 | 20 | 30 | 40 | 50 ]
  ^                            ^
 Delete                      Insert

Basic Operations:

  • Enqueue: Insert an element at the rear
  • Dequeue: Remove an element from the front
  • Peek/Front: View the front element without removing it

Three Types of Graphs [3 marks]

A graph is a non-linear data structure consisting of a set of vertices (nodes) and edges (connections) represented as G = (V, E).


1. Directed Graph (Digraph)

A graph in which every edge has a specific direction is called a directed graph. The edges are represented as ordered pairs (u, v), meaning the edge goes from vertex u to vertex v but not necessarily from v to u.

    A -----> B
    |        |
    v        v
    C -----> D
  • Edge (A, B) means A points to B
  • Used in: web page linking, task scheduling

2. Undirected Graph

A graph in which edges have no direction is called an undirected graph. The edges are represented as unordered pairs {u, v}, meaning the connection is bidirectional.

    A ----- B
    |       |
    |       |
    C ----- D
  • Edge {A, B} means both A connects to B and B connects to A
  • Used in: social networks, road maps

3. Weighted Graph

A graph in which each edge is assigned a numerical value (weight or cost) is called a weighted graph. It can be either directed or undirected.

    A ---5--- B
    |         |
    3         7
    |         |
    C ---2--- D
  • The weight may represent distance, cost, time, or capacity
  • Used in: shortest path algorithms (Dijkstra's), network routing, GPS navigation

Note: Other types include cyclic/acyclic graphs, connected/disconnected graphs, and complete graphs.

Open this answer on its own page →

Postfix expression evaluation algorithm

2080 · 10 marks

What is stack? Explain different stack operations. Explain algorithm to evaluate postfix expression.[10]

Show solved answer

Stack: Definition, Operations, and Postfix Evaluation


1. What is a Stack?

A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. This means the element inserted last is the first one to be removed.

A stack can be visualized as a pile of plates: you add a plate on top and also remove from the top.

Key characteristics:

  • All insertions and deletions occur at one end called the TOP
  • It is an ordered collection of elements
  • It can be implemented using arrays or linked lists

2. Stack Operations

The following are the primary operations performed on a stack:

a) PUSH (Insertion)

Adds an element to the top of the stack.

Algorithm: PUSH(STACK, TOP, MAXSIZE, ITEM)

1. If TOP = MAXSIZE - 1, then:
      Print "Stack Overflow" and EXIT
2. Set TOP = TOP + 1
3. Set STACK[TOP] = ITEM
4. Return

b) POP (Deletion)

Removes and returns the top element from the stack.

Algorithm: POP(STACK, TOP, ITEM)

1. If TOP = -1, then:
      Print "Stack Underflow" and EXIT
2. Set ITEM = STACK[TOP]
3. Set TOP = TOP - 1
4. Return ITEM

c) PEEK / TOP

Returns the top element without removing it.

1. If TOP = -1, then:
      Print "Stack is Empty" and EXIT
2. Return STACK[TOP]

d) isEmpty

Checks whether the stack is empty.

1. If TOP = -1, return TRUE
2. Else return FALSE

e) isFull

Checks whether the stack is full.

1. If TOP = MAXSIZE - 1, return TRUE
2. Else return FALSE

3. Postfix Expression Evaluation

What is a Postfix Expression?

In postfix notation (also called Reverse Polish Notation), the operator comes after its operands.

  • Infix: A + B
  • Postfix: A B +

Postfix expressions do not require parentheses and are easy to evaluate using a stack.


Algorithm to Evaluate Postfix Expression

Input: A postfix expression string
Output: The evaluated result

Algorithm EVALUATE_POSTFIX(expression):

1. Create an empty stack S
2. Scan the expression from LEFT to RIGHT, one token at a time
3. For each token:
      a. If token is an OPERAND (number):
            PUSH it onto stack S
      b. If token is an OPERATOR (+, -, *, /):
            i.  POP the top element, call it OPERAND2
            ii. POP the next top element, call it OPERAND1
            iii.Apply the operator: RESULT = OPERAND1 operator OPERAND2
            iv. PUSH RESULT onto stack S
4. After scanning all tokens:
      POP and return the final value from stack S
      (This is the result of the expression)

Note: The order matters: first popped value is the right operand, second popped value is the left operand.


Worked Example

Evaluate postfix expression: 5 3 + 2 * 4 -

StepTokenActionStack State
15PUSH 5[5]
23PUSH 3[5, 3]
3+POP 3 and 5, compute 5+3=8, PUSH 8[8]
42PUSH 2[8, 2]
5*POP 2 and 8, compute 8*2=16, PUSH 16[16]
64PUSH 4[16, 4]
7-POP 4 and 16, compute 16-4=12, PUSH 12[12]

Final Result = 12


Another Example

Evaluate: 6 2 3 + - 3 8 2 / + *

TokenActionStack
6PUSH[6]
2PUSH[6, 2]
3PUSH[6, 2, 3]
+POP 3,2 → 2+3=5, PUSH[6, 5]
-POP 5,6 → 6-5=1, PUSH[1]
3PUSH[1, 3]
8PUSH[1, 3, 8]
2PUSH[1, 3, 8, 2]
/POP 2,8 → 8/2=4, PUSH[1, 3, 4]
+POP 4,3 → 3+4=7, PUSH[1, 7]
*POP 7,1 → 1*7=7, PUSH[7]

Final Result = 7


Summary

OperationDescriptionTime Complexity
PUSHInsert element at topO(1)
POPRemove element from topO(1)
PEEKView top elementO(1)
isEmptyCheck if stack is emptyO(1)
isFullCheck if stack is fullO(1)
Postfix EvaluationScan and computeO(n)

Every basic stack operation touches only the top of the stack, so each of them runs in constant time. Postfix evaluation scans the expression once and performs a constant amount of work per token, so it is O(n) in time and O(n) in space for the stack in the worst case, where n is the number of tokens.


Conclusion

A stack is a linear list restricted to LIFO access through PUSH and POP at a single end, with PEEK, isEmpty and isFull as supporting operations. Its usefulness is best seen in expression evaluation: because postfix notation carries no parentheses and no precedence, a single left to right scan with one stack is enough, pushing every operand and replacing the top two operands by the result whenever an operator appears. The value left on the stack at the end of the scan is the value of the expression.

Open this answer on its own page →

Queue implementation using linked list

2080 · 5 marks

How can we use linked list to implement queue? Explain. [5]

A queue is a linear data structure that follows the FIFO (First In, First Out) principle. Using a linked list to implement a queue allows dynamic memory allocation, avoiding the fixed-size limitation of array-based queues. --- Each node in the linked list contains: - data - the value stored - nex...

Open this answer on its own page →

2078 · 5 marks

How can you implement queue using linked list? Explain. [5]

A queue is a linear data structure that follows the FIFO (First In, First Out) principle. Using a linked list to implement a queue allows dynamic memory allocation, avoiding the fixed-size limitation of array-based queues. Two pointers are maintained: - FRONT -- points to the first node (for dele...

Open this answer on its own page →

Priority queue definition and implementation

2079 · 5 marks

Explain priority queue with example. What is circular queue? [5]

A priority queue is a special type of queue in which each element is associated with a priority value, and elements are served (removed) based on their priority rather than their insertion order. - An element with higher priority is dequeued before an element with lower priority. - If two element...

Open this answer on its own page →

2078 · 5 marks

Define priority queue. How do you implement priority queue? Explain. [5]

A priority queue is an abstract data type (ADT) similar to a regular queue, but each element has an associated priority value. Elements are served (removed) based on their priority rather than their insertion order: - The element with the highest priority is dequeued first. - If two elements have...

Open this answer on its own page →

Differentiation between stack and queue

0 · 10 marks

Differentiate stack with queue? Trace an algorithm for converting infix expression to postfix for the following infix expression: (A+B)*(C$(D-E)+F)-G[10]

Feature Stack Queue --------- Principle LIFO (Last In First Out) FIFO (First In First Out) Insertion/Deletion Both at the same end (top) Insertion at rear, deletion at front Operations PUSH (insert), POP (delete) ENQUEUE (insert), DEQUEUE (delete) Number of ends used One (top) Two (front and rear...

Open this answer on its own page →