Stacks, a fundamental data structure in computer science, are crucial for understanding algorithmic paradigms and solving complex computational problems. As candidates gear up for the GATE Exam 2024, a solid grasp of stack concepts is indispensable. These notes are designed to provide a concise yet comprehensive overview of stacks, covering key topics that are likely to be assessed in the GATE examination.

Table of Content

- Introduction to Stack:
- LIFO (Last In First Out) in Stack:
- Basic Operations on Stack
- Implementation of Stack using Singly Linked List:
- Applications, Advantages and Disadvantages of Stack:
- Infix to Postfix Operation in Stack:
- Postfix Evaluation using Stack:
- Towers of Hanoi using Stack:
- Fibonaaci Series using Stack:
- Previously Asked GATE Questions on Stack:

## Introduction to Stack:

A stack is a linear data structure in which the insertion of a new element and removal of an existing element takes place at the same end represented as the top of the stack.

To implement the stack, it is required to maintain the ** pointer to the top of the stack**, which is the last element to be inserted because

**we can access the elements only on the top of the stack.****LIFO (Last In First Out) in Stack****:**

**LIFO (Last In First Out) in Stack**

**:**This strategy states that the element that is inserted last will come out first. You can take a pile of plates kept on top of each other as a real-life example. The plate which we put last is on the top and since we remove the plate that is at the top, we can say that the plate that was put last comes out first.

__Basic Operations on Stack__

In order to make manipulations in a stack, certain operations are provided to us.

to insert an element into the stack**push()**to remove an element from the stack**pop()**Returns the top element of the stack.**top()**returns true if the stack is empty else false.**isEmpty()**returns the size of the stack.**size()**

**Time Complexity of Stack Operations:**

**Time Complexity of Stack Operations:**Operations |
Complexity |
---|---|

push() | O(1) |

pop() | O(1) |

isEmpty() | O(1) |

size() | O(1) |

## Implementation of Stack using Singly Linked List:

To implement a stack using the singly linked list concept, all the singly linked list operations should be performed based on Stack operations LIFO(last in first out) and with the help of that knowledge, we are going to implement a stack using a singly linked list.

So we need to follow a simple rule in the implementation of a stack which is ** last in first out** and all the operations can be performed with the help of a top variable. Let us learn how to perform

**operations in the following article:**

**Pop, Push, Peek, and Display**In the stack Implementation, a stack contains a top pointer. which is the “head” of the stack where pushing and popping items happens at the head of the list. The first node has a null in the link field and second node-link has the first node address in the link field and so on and the last node address is in the “top” pointer.

The main advantage of using a linked list over arrays is that it is possible to implement a stack that can shrink or grow as much as needed. Using an array will put a restriction on the maximum capacity of the array which can lead to stack overflow. Here each new node will be dynamically allocated. so overflow is not possible.

**Push Operation:**

- Initialise a node
- Update the value of that node by data i.e.
node->data = data- Now link this node to the top of the linked list
- And update top pointer to the current node

**Pop Operation:**

- First Check whether there is any node present in the linked list or not, if not then return
- Otherwise make pointer let say
to the top node and move forward the top node by 1 steptemp- Now free this temp node

**Peek Operation:**

- Check if there is any node present or not, if not then return.
- Otherwise return the value of top node of the linked list

**Display Operation:**

- Take a
node and initialize it with top pointertemp- Now start traversing temp till it encounters NULL
- Simultaneously print the value of the temp node

## Applications, Advantages and Disadvantages of Stack:

**Application of Stack Data Structure:**

**Application of Stack Data Structure:**When a function is called, the current state of the program is pushed onto the stack. When the function returns, the state is popped from the stack to resume the previous function’s execution.**Function calls and recursion:**The undo-redo feature in various applications uses stacks to keep track of the previous actions. Each time an action is performed, it is pushed onto the stack. To undo the action, the top element of the stack is popped, and the reverse operation is performed.**Undo/Redo operations:**Stack data structure is used to evaluate expressions in infix, postfix, and prefix notations. Operators and operands are pushed onto the stack, and operations are performed based on the stack’s top elements.**Expression evaluation:**Web browsers use stacks to keep track of the web pages you visit. Each time you visit a new page, the URL is pushed onto the stack, and when you hit the back button, the previous URL is popped from the stack.**Browser history:**Stack data structure is used to check if parentheses are balanced or not. An opening parenthesis is pushed onto the stack, and a closing parenthesis is popped from the stack. If the stack is empty at the end of the expression, the parentheses are balanced.**Balanced Parentheses:**The backtracking algorithm uses stacks to keep track of the states of the problem-solving process. The current state is pushed onto the stack, and when the algorithm backtracks, the previous state is popped from the stack.**Backtracking Algorithms:**

**Advantages of Stack:**

**Advantages of Stack:**Stack data structure is easy to implement using arrays or linked lists, and its operations are simple to understand and implement.**Easy implementation:**: Stack uses a contiguous block of memory, making it more efficient in memory utilization as compared to other data structures.**Efficient memory utilization**Stack data structure provides fast access time for adding and removing elements as the elements are added and removed from the top of the stack.**Fast access time:**Stack data structure is used to store function calls and their states, which helps in the efficient implementation of recursive function calls.**Helps in function calls:**Stack data structure supports backtracking algorithms, which are used in problem-solving to explore all possible solutions by storing the previous states.**Supports backtracking:**Stack data structure is used in compiler design for parsing and syntax analysis of programming languages.**Used in Compiler Design:**: Stack data structure is used to enable undo and redo operations in various applications like text editors, graphic design tools, and software development environments.**Enables undo/redo operations**

**Disadvantages of Stack: **

**Disadvantages of Stack:**Stack data structure has a limited capacity as it can only hold a fixed number of elements. If the stack becomes full, adding new elements may result in stack overflow, leading to the loss of data.**Limited capacity:**Stack data structure does not allow for random access to its elements, and it only allows for adding and removing elements from the top of the stack. To access an element in the middle of the stack, all the elements above it must be removed.**No random access:**Stack data structure uses a contiguous block of memory, which can result in memory fragmentation if elements are added and removed frequently.**Memory management:**Stack data structure is not suitable for applications that require accessing elements in the middle of the stack, like searching or sorting algorithms.**Not suitable for certain applications:**: Stack data structure can result in stack overflow if too many elements are pushed onto the stack, and it can result in stack underflow if too many elements are popped from the stack.**Stack overflow and underflow**While stack data structure supports recursive function calls, too many recursive function calls can lead to stack overflow, resulting in the termination of the program.**Recursive function calls limitations:**

## Infix to Postfix Operation in Stack:

To convert infix expression to postfix expression, use the

. Scan the infix expression from left to right. Whenever we get an operand, add it to the postfix expression and if we get an operator or parenthesis add it to the stack by maintaining their precedence.stack data structure

Below are the steps to implement the above idea:

- Scan the infix expression
.**from left to right** - If the scanned character is an operand, put it in the postfix expression.
- Otherwise, do the following
- If the precedence and associativity of the scanned operator are greater than the precedence and associativity of the operator in the stack [or the stack is empty or the stack contains a ‘
‘ ], then push it in the stack. [‘**(**‘ operator is right associative and other operators like ‘**^**‘,’**+**‘,’**–**‘ and ‘*****‘ are left-associative].**/**- Check especially for a condition when the operator at the top of the stack and the scanned operator both are ‘
‘. In this condition, the precedence of the scanned operator is higher due to its right associativity. So it will be pushed into the operator stack.**^** - In all the other cases when the top of the operator stack is the same as the scanned operator, then pop the operator from the stack because of left associativity due to which the scanned operator has less precedence.

- Check especially for a condition when the operator at the top of the stack and the scanned operator both are ‘
- Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator.
- After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.)

- If the precedence and associativity of the scanned operator are greater than the precedence and associativity of the operator in the stack [or the stack is empty or the stack contains a ‘
- If the scanned character is a ‘
‘, push it to the stack.**(** - If the scanned character is a ‘
’, pop the stack and output it until a ‘**)**‘ is encountered, and discard both the parenthesis.**(** - Repeat steps
until the infix expression is scanned.**2-5** - Once the scanning is over, Pop the stack and add the operators in the postfix expression until it is not empty.
- Finally, print the postfix expression.

## Postfix Evaluation using Stack:

To evaluate a postfix expression we can use a stack.

Iterate the expression from left to right and keep on storing the operands into a stack. Once an operator is received, pop the two topmost elements and evaluate them and push the result in the stack again.

## Towers of Hanoi using Stack:

Tower of Hanoi is a mathematical puzzle where we have three rods (** A**,

**, and**

**B****) and**

**C****disks. Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest disk is placed on the top and they are on rod**

**N****. The objective of the puzzle is to move the entire stack to another rod (here considered**

**A****), obeying the following simple rules:**

**C**- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
- No disk may be placed on top of a smaller disk.

**Examples:**

Input:3Output:Disk 1 moved from A to CDisk 2 moved from A to BDisk 1 moved from C to BDisk 3 moved from A to CDisk 1 moved from B to ADisk 2 moved from B to CDisk 1 moved from A to C

**Tower of Hanoi using Recursion:**

The idea is to use the helper node to reach the destination using recursion. Below is the pattern for this problem:

- Shift ‘N-1’ disks from ‘A’ to ‘B’, using C.
- Shift last disk from ‘A’ to ‘C’.
- Shift ‘N-1’ disks from ‘B’ to ‘C’, using A.

Follow the steps below to solve the problem:

- Create a function
where pass the**towerOfHanoi**(current number of disk),**N**,**from_rod**,**to_rod****aux_rod.** - Make a function call for N – 1 th disk.
- Then print the current the disk along with
and**from_rod****to_rod** - Again make a function call for N – 1 th disk.

** Time complexity**: O(2

^{N}), There are two possibilities for every disk. Therefore, 2 * 2 * 2 * . . . * 2(N times) is 2

^{N}

**O(N), Function call stack space**

**Auxiliary Space:**## Fibonaaci Series using Stack:

The Fibonacci numbers are the numbers in the following integer sequence:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

**Example:**

n = 9Input :

34Output :

*In mathematical terms, the sequence Fn of ***Fibonacci ***numbers is defined by the recurrence relation: *

## Previously Asked GATE Questions on Stack:

**Question 1:**

The end of a stack, traditionally known as the position where PUSH and POP operations performed, is known as:

- FIFO
- LIFO
- FRONT
- TOP

Option 4 : TOPAnswer:ExplanationThe top of the stack refers to the end of the stack where operations are performed. This is where elements are added (pushed) and removed (popped). When an element is added to an empty stack, it becomes the top element. When additional elements are pushed onto the stack, they become the new top elements.:

**Question 2:**

What is the equivalent infix expression of the following postfix expression?

M, N, O, +, *, P, /, Q, R, S, T, /, +, *, –

- N*(M+Q)/Q-P*(S+R/T)
- (((M*(N+O))/P)-(Q*(R+(S/T))))
- O * (M + N)/P – Q * (R + S/T)
- M * (N + O)/Q – P * (R/S + T)

Option 2 : (((M * (N + O)) / P) – (Q * (R + (S / T))))Answer:Explanation:Let’s apply this algorithm to the given postfix

expression – M, N, O, +, *, P, /, Q, R, S, T, /, +, *, –Step 1 – Push M, N, O onto the stack Stack – O, N, M

Step 2 – Pop O, N, M and concatenate them with + and * Stack – (M*(N+O))

Step 3 – Push P onto the stack Stack – P, (M*(N+O))

Step 4 – Pop P and concatenate it with / Stack – ((M*(N+O))/P)

Step 5 – Push Q, R, S, T onto the stack Stack – T, S, R, Q, ((M*(N+O))/P)

Step 6 – Pop T, S, R, Q and concatenate them with / and + and * Stack – ((Q*(R+(S/T))), ((M*(N+O))/P)

Step 7 – Pop the final expression from the stack after “-” Infix expression – (((M*(N+O))/P) – ((Q*(R+(S/T))))

**Question 3:**

What is the postfix representation of the following infix expression?

(A + B) * C – D * E / F

- A B + C * D E * F – /
- A B * C + D E * F / –
- A B + C – D E * F / *
- A B + C * D E * F / –

Option 4 : A B + C * D E * F / –Answer:Explanation:() has highest precedence

* and / has same precedence while + and – has same precedence

(* and /) and higher precedence than (+, -)

Associativity is left to right:

(A + B) * C – D * E / F

* C – D * E / FA B +

– D * E / FA B + C *

–A B + C */ FD E *

–A B + C *D E * F /

A B + C * D E * F / –

**Question 4:**

The result evaluating the postfix expression 10 5 + 60 6 / * 8 − is

**284****213****142****71**

Option 3 : 142Answer:

**Question 5:**

The five items P,Q,R,S and T are pushed in a stack, one after the other starting from P. The stack is popped four times and each element is inserted in a queue. Then two elements are deleted from the queue and pushed back on the stack. now one item is popped from the stack. The popped item is:

- P
- R
- Q
- S

Option 4 : SAnswer:

**Question 6: **

Consider the following postfix expression with single digit operands:

6 2 3 * / 4 2 * + 6 8 * –

The top two elements of the stack after second * is evaluated, are:

**6, 3****8, 1****8, 2****6, 2**

Option 2 : 8, 1Answer:

**Question 7:**

What is the outcome of the prefix expression +, -, *, 3, 2, /, 8, 4, 1?

**12****5****11****4**

Answer:Option 2 : 5

**Question 8: **

A stack is implemented with an array of ‘A [0..N – 1]’ and a variable ‘pos’. The push and pop operations are defined by the following code.

push(x)

A[pos] ← x

pos ← pos – 1

end push

pop( )

pos ← pos + 1

return A[pos]

end pop

Which of the following will initialize an empty stack with capacity N for the above implementation?

- pos ← -1
- pos ← 0
- pos ← 1
- pos ← N – 1

AnswerOption 4 : pos ← N – 1:

**Question 9:**

A stack can be implemented using queue, but then we need to use atleast:

- 3 queues
- 2 queues
- only one queue is sufficient
- none of the options

AnswerOption 2 : 2 queues:

**Question 10:**

Which of the following applications may use a stack?

(a) Parenthesis balancing program

(b) Process scheduling operating system

(c) Conversion of infix arithmetic expression to postfix form

- (a) and (b)
- (b) and (c)
- (a) and (c)
- (a), (b) and (c)

Option 3 : (a) and (c)Answer: