2 Stack

Data Structures and Algorithms ยท Unit 2 ยท 4 hrs

Stack

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

Stack in short

This chapter introduces the stack, the simplest of the restricted access linear data structures, its array and linked list implementations, and its best known application: converting and evaluating arithmetic expressions written in infix, prefix and postfix notation.

Stack: notes

Basic Concept of Stack, Stack as an ADT, Stack Operations

A stack is a linear data structure in which insertion and deletion both happen at the same end, called the top. It follows the Last In First Out (LIFO) discipline: the element inserted most recently is the first one removed, exactly like a stack of plates. Inserting an element is a push, which increments top; removing an element is a pop, which decrements top. As an abstract data type, a stack $S$ of type $T$ supports:

  • CreateEmptyStack(S): create an empty stack.
  • Push(S, x): insert x at the top of S.
  • Pop(S): remove and return the element at the top of S, if S is not empty.
  • Top(S): return the top element without removing it.
  • IsEmpty(S) / IsFull(S): report whether S is empty or full.

Using a fixed size array stack[MAXSIZE] and an integer top initialised to $-1$ for an empty stack:

#include <stdio.h>

#define MAXSIZE 10

int stack[MAXSIZE];
int top = -1;

int isFull(void)  { return top == MAXSIZE - 1; }
int isEmpty(void) { return top == -1; }

void push(int item) {
    if (isFull()) {
        printf("Stack Overflow\n");
        return;
    }
    stack[++top] = item;
}

int pop(void) {
    if (isEmpty()) {
        printf("Stack Underflow\n");
        return -1;
    }
    return stack[top--];
}

push fails with a stack overflow when top == MAXSIZE - 1; pop fails with a stack underflow when top == -1. Both operations run in $O(1)$ time since they only touch the top of the array. Since a fixed array cannot regrow, a stack can also be built on a singly linked list, where top is a pointer to the first node instead of an array index:

What this unit covers

  • Basic Concept of Stack, Stack as an ADT, Stack Operations, Stack Applications
  • Conversion from infix to postfix/prefix expression, Evaluation of postfix/ prefix expressions

Conversion from infix to postfix/prefix expression, Evaluation of postfix/ prefix expressions

2081 ยท 5 marks

Convert the infix expression A+(((B-C)*(D-E)+F)/G$(H-I) into post expression using stack. [5]

Show solved answer

Infix to Postfix Conversion Using Stack

Given

Infix expression: A+(((B-C)*(D-E)+F)/G$(H-I))

Note: The original problem text shows an apparent typo with unbalanced parentheses. Counting the brackets:

  • Open parens: ( before ((, giving 4 opening: ( ( ( (
  • Actually reading A+(((B-C)*(D-E)+F)/G$(H-I)) the balanced form has 4 opens and 4 closes.

I take the balanced expression: A+(((B-C)*(D-E)+F)/G$(H-I))

Operator precedence ($ = exponentiation, highest):

OperatorPrecedence
$Highest
*, /Medium
+, -Lowest

$ is right-associative; *, /, +, - are left-associative.


Solution

SymbolActionStack (bottomโ†’top)Postfix
AoutputA
+push+A
(push+ (A
(push+ ( (A
(push+ ( ( (A
Boutput+ ( ( (A B
-push+ ( ( ( -A B
Coutput+ ( ( ( -A B C
)pop to (+ ( (A B C -
*push+ ( ( *A B C -
(push+ ( ( * (A B C -
Doutput+ ( ( * (A B C - D
-push+ ( ( * ( -A B C - D
Eoutput+ ( ( * ( -A B C - D E
)pop to (+ ( ( *A B C - D E -
+pop *, push ++ ( ( +A B C - D E - *
Foutput+ ( ( +A B C - D E - * F
)pop to (+ (A B C - D E - * F +
/push+ ( /A B C - D E - * F +
Goutput+ ( /A B C - D E - * F + G
$push+ ( / $A B C - D E - * F + G
(push+ ( / $ (A B C - D E - * F + G
Houtput+ ( / $ (A B C - D E - * F + G H
-push+ ( / $ ( -A B C - D E - * F + G H
Ioutput+ ( / $ ( -A B C - D E - * F + G H I
)pop to (+ ( / $A B C - D E - * F + G H I -
)pop $, /, to (+A B C - D E - * F + G H I - $ /
Endpop all(empty)A B C - D E - * F + G H I - $ / +

Explanation of key steps:

  • At the + after (D-E): top of stack (inside brackets) is *, which has higher precedence than +, so * is popped, then + is pushed.
  • At final ): pop $ then / until matching (.
  • At End: pop remaining +.

Final Postfix Expression

$$\boxed{A\ B\ C-D\ E-*\ F+G\ H\ I-$\ /\ +}$$

That is: ABC-DE-*F+GHI-$/+

Verification: evaluating the postfix from left to right, A B C - builds (B-C), D E - builds (D-E), the * multiplies them, F + adds F, then G H I - $ builds G raised to (H-I), the / divides the bracketed sum by it, and the final + adds A, which reproduces the original infix expression exactly. The stack is empty at the end and every opening parenthesis was matched by a closing one, so the conversion is complete and correct.

Open this answer on its own page โ†’

2079 ยท 10 marks

How recursive algorithm uses stack to store intermediate results? Illustrate with an example. Convert the infix expression A+B*(C/D+F)-G/H into postfix expression using stack.[10]

  • Task 1: Explain how a recursive algorithm uses a stack for intermediate results, with an example. - Task 2 (numeric/symbolic): Infix expression to convert to postfix: $$A + B \times (C / D + F) - G / H$$ - Method required: Stack-based conversion. - Marks: 10. Nothing missing. --- A recursive al...
Open this answer on its own page โ†’

2079 ยท 5 marks

Evaluate the postfix expression 574-*8/4+ using stack. [5]

Show solved answer

Evaluating Postfix Expression: 5 7 4 - * 8 / 4 +

Given Data

  • Postfix expression: 5 7 4 - * 8 / 4 +
  • Data structure to use: Stack

Algorithm (Postfix Evaluation)

  1. Scan the expression left to right.
  2. If the symbol is an operand, push it onto the stack.
  3. If the symbol is an operator, pop the top two operands:
    • op2 = first pop (right operand)
    • op1 = second pop (left operand)
    • Compute op1 <operator> op2 and push the result.
  4. The final remaining stack element is the result.

Step-by-Step Trace

StepSymbolActionStack (bottom โ†’ top)
15Push 55
27Push 75, 7
34Push 45, 7, 4
4-Pop 4, Pop 7 โ†’ $7 - 4 = 3$; Push 35, 3
5*Pop 3, Pop 5 โ†’ $5 \times 3 = 15$; Push 1515
68Push 815, 8
7/Pop 8, Pop 15 โ†’ $15 / 8$; Push result...
84Push 4(result), 4
9+Pop 4, Pop (result) โ†’ add; Pushfinal

Handling the Division at Step 7

The value $15 / 8 = 1.875$.

Case A: Integer division (common in textbook/C-style examples): $$15 / 8 = 1$$ Then:

  • Step 8: Push 4 โ†’ stack: 1, 4
  • Step 9: $1 + 4 = 5$

Final result = 5

Case B: Real (floating-point) division: $$15 / 8 = 1.875$$ Then:

  • Step 8: Push 4 โ†’ stack: 1.875, 4
  • Step 9: $1.875 + 4 = 5.875$

Final result = 5.875


Result

Since this is a data structures problem typically evaluated with integer arithmetic, the standard exam answer is:

$$\boxed{5\ 7\ 4\ -\ *\ 8\ /\ 4\ +\ =\ 5}$$

(If real-number division is intended, the result would be $5.875$.)

The trace gives a final value of 5 (using integer division).

Open this answer on its own page โ†’

2078 ยท 5 marks

Evaluate the expression ABCD-x+ using stack where A=5, B=4, C=3 and D=7. [5]

  • Postfix expression: A B C D - x + where x denotes multiplication - Operand values: - $A = 5$ - $B = 4$ - $C = 3$ - $D = 7$ So the expression to evaluate is: A B C D - + --- - Scan left to right. - Operand โ†’ push onto stack. - Operator โ†’ pop top two operands, apply operator as (second popped) op...
Open this answer on its own page โ†’

2077 ยท 5 marks

Explain algorithm for evaluation of postfix expression using stack. [5]

In a postfix expression (also called Reverse Polish Notation), operators follow their operands. A stack is used to hold operands until an operator is encountered, at which point the operation is performed. --- 1. Scan the postfix expression from left to right, one symbol at a time. 2. If the scan...

Open this answer on its own page โ†’

2075 ยท 10 marks

How can you use stack to convert an infix expression to postfix? Convert infix expression (A+B)*(C-D) to postfix using stack.[10]

A stack is used to temporarily hold operators and parentheses so that operators are emitted to the output in the correct order of precedence. We scan the infix expression left to right and apply the following rules: 1. Operand โ†’ append directly to the postfix output. 2. Opening parenthesis ( โ†’ pu...

Open this answer on its own page โ†’

2074 ยท 5 marks

Explain the infix to post fix conversion algorithm. [5]

Infix notation is the standard mathematical notation where operators are placed between operands (e.g., A + B). Postfix notation (Reverse Polish Notation) places operators after their operands (e.g., A B +). The conversion uses a stack data structure to temporarily hold operators and parentheses....

Open this answer on its own page โ†’

Basic Concept of Stack, Stack as an ADT, Stack Operations, Stack Applications

2080 ยท 5 marks

Explain push and pop operations of stack. What are different applications of stack? [5]

A stack is a linear data structure in which insertion and deletion of elements takes place at only one end, called the top. It follows the LIFO (Last In First Out) principle, meaning the last element inserted is the first one to be removed. --- The PUSH operation is used to insert/add an element ...

Open this answer on its own page โ†’

2077 ยท 10 marks

What is stack? What are the different applications of stack? Explain stack operations with example.[10]

Show solved answer

Stack: Definition, Applications, and Operations

1. What is a Stack?

A stack is a linear data structure in which an element may be inserted or deleted only at one end (called the top of the stack). Elements are removed from a stack in the reverse order of that in which they were inserted.

Stack follows the principle of LIFO (Last In First Out), meaning the last element inserted is the first one to be removed.

Stack uses a variable called top which always points to the topmost element in the stack.

Example: Consider a stack of plates. You can only add or remove a plate from the top.

     |  30  |  <-- top
     |  20  |
     |  10  |
     |______|

2. Applications of Stack

#ApplicationDescription
1Expression EvaluationUsed to evaluate arithmetic expressions (postfix/prefix)
2Infix to Postfix ConversionOperators are pushed/popped using stack based on precedence
3Function Call ManagementSystem uses call stack to manage function calls and returns
4RecursionEach recursive call is stored on the stack until base case is reached
5Undo/Redo OperationsText editors use stack to undo or redo operations
6BacktrackingUsed in maze solving, puzzle solving algorithms
7Syntax ParsingCompilers use stack to check balanced parentheses and syntax
8Browser HistoryBack button in browsers uses stack to track visited pages

3. Stack Operations

There are two primary operations on a stack:

a) PUSH Operation

The PUSH operation is used to add or insert an element into the stack.

  • The element is always added at the top of the stack.
  • Top is incremented when PUSH operation occurs.
  • Before pushing, we check for Overflow condition (stack is full).

Overflow Condition: If top == MAX - 1, the stack is full and no more elements can be pushed.

Algorithm for PUSH:

Algorithm PUSH(stack, top, MAX, item):
  Step 1: If top == MAX - 1 then
              Print "Stack Overflow"
              Return
  Step 2: top = top + 1
  Step 3: stack[top] = item
  Step 4: Return

Example of PUSH:

Push elements 10, 20, 30 one by one:

Initial Stack:        After PUSH(10):     After PUSH(20):     After PUSH(30):
  top = -1              top = 0             top = 1             top = 2
  |      |              |  10  |            |  20  |            |  30  | <-- top
  |      |              |      |            |  10  |            |  20  |
  |      |              |      |            |      |            |  10  |
  |______|              |______|            |______|            |______|

b) POP Operation

The POP operation is used to delete or remove an element from the stack.

  • The element is always removed from the top of the stack.
  • Top is decremented when POP operation occurs.
  • Before popping, we check for Underflow condition (stack is empty).

Underflow Condition: If top == -1, the stack is empty and no element can be popped.

Algorithm for POP:

Algorithm POP(stack, top):
  Step 1: If top == -1 then
              Print "Stack Underflow"
              Return
  Step 2: item = stack[top]
  Step 3: top = top - 1
  Step 4: Return item

Example of POP:

Pop elements from the stack containing 30, 20, 10:

Initial Stack:        After POP():        After POP():        After POP():
  top = 2               top = 1             top = 0             top = -1
  |  30  | <-- top      |  20  | <-- top    |  10  | <-- top    |      |
  |  20  |              |  10  |            |      |            |      |
  |  10  |              |      |            |      |            |      |
  |______|              |______|            |______|            |______|
  Popped: 30            Popped: 20          Popped: 10          Stack Empty

c) PEEK / Top Operation

Returns the topmost element without removing it.

Algorithm PEEK(stack, top):
  Step 1: If top == -1 then
              Print "Stack is Empty"
              Return
  Step 2: Return stack[top]

4. Complete Example: Infix to Postfix Conversion Using Stack

Convert infix expression (A + B / C * D + E) - F to postfix using stack.

The precedence rules used:

  • ^ or $ -- Highest (Level 1)
  • *, / -- Medium (Level 2)
  • +, - -- Lowest (Level 3)
Symbol ScannedStackPostfix
((
A(A
+( +A
B( +A B
/( + /A B
C( + /A B C
*( + *A B C /
D( + *A B C / D
+( +A B C / D * +
E( +A B C / D * + E
)EmptyA B C / D * + E +
--A B C / D * + E +
F-A B C / D * + E + F
EndEmptyA B C / D * + E + F -

When the second + is scanned, the * already on the stack and the + below it both have precedence at least as high as the incoming +, so both are popped to the output before the new + is pushed. Emptying the stack at the end gives

Postfix: A B C / D * + E + F -

The stack made this conversion possible because operators must be held back until an operator of lower or equal precedence, or a closing parenthesis, appears, and a stack returns them in exactly the reverse order in which they were held.


5. Conclusion

A stack is a linear structure restricted to a single access point, the top, which gives it LIFO behaviour and makes PUSH, POP and PEEK all constant time operations once the overflow and underflow conditions have been checked. That single restriction is precisely what makes it useful: function calls and recursion unwind in reverse order of their invocation, undo history is replayed backwards, backtracking abandons the most recent choice first, and expression conversion and evaluation need operators released in reverse order of their being held. Whether it is implemented over an array with an integer top or over a linked list with a head pointer, the behaviour seen by the user of the ADT stays the same.

Open this answer on its own page โ†’

2075 ยท 5 marks

Compare stack with queue. How is linear queue different from circular queue? [5]

--- Basis Stack Queue --------- Principle Last In First Out (LIFO) First In First Out (FIFO) End of Operation Insertion and deletion both occur at one end called the top Insertion occurs at the rear end and deletion occurs at the front end Operations PUSH (insert) and POP (delete) Enqueue (insert...

Open this answer on its own page โ†’

2075 ยท 5 marks

What is ADT? Discuss stack as an ADT. [5]

--- Definition: An Abstract Data Type (ADT) is a type or a class for objects whose behaviour is defined by a set of values and a set of operations. It does not specify how data will be organized in memory and what algorithms will be used for implementing the operations. In simple terms, ADT descr...

Open this answer on its own page โ†’