Docsity

Understanding Stacks: LIFO Data Structure Explained, Lecture notes of Data Structures and Algorithms

Partial preview of the text

Download Understanding Stacks: LIFO Data Structure Explained and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

Data

Structures

and

Algorithms

C H A P TER F O UR : STA C KS DATA STRUCTURES AND ALGORITHM BY: KIBRU G.

Outline

▪ Introduction to Stack ▪ Definition ▪ Characteristics (LIFO - Last In, First Out) ▪ Basic Operations (Push, Pop, Peek, IsEmpty, IsFull ▪ Properties of Stack ▪ Order of execution (LIFO) ▪ Fixed vs. Dynamic size ▪ Memory allocation (contiguous vs. non-contiguous) ▪ Array Implementation of Stack ▪ Linked List Implementation of Stack ▪ Application of Stack ▪ Evaluation of Algebraic Expression ▪ Infix and Post fix (RPN) conversion

▪ Stack of Plates: You can only take the top plate.

▪ Browser History: The "Back" button works in LIFO order.

▪ Function Call Stack: Tracks active subroutines in a program.

Introduction to Stack

▪ LIFO Principle (Last In, First Out) ▪ The last element pushed (inserted) is the first one popped (removed). ▪ Example: ▪ Push A → Stack: [A] ▪ Push B → Stack: [A, B] (Top = B) ▪ Pop → Returns B, Stack: [A] ▪ Limited Access ▪ Only the top element is accessible. ▪ No direct access to middle or bottom elements (unlike arrays). ▪ Dynamic or Fixed Size ▪ Can be implemented with dynamic resizing (e.g., linked list ) or fixed capacity (e.g., array-based stack ).

Characteristics of a Stack

▪Stacks can have either fixed or dynamic sizes based on their implementation. ▪ Fixed-size Stack (Array-based): ▪ The size of the stack is predefined and cannot change during execution. ▪ Once the stack reaches its maximum size, no more elements can be added (Stack Overflow). ▪ Efficient in terms of memory allocation but lacks flexibility. ▪ Dynamic-size Stack (Linked List-based): ▪ The size of the stack grows and shrinks dynamically based on the number of elements. ▪ There is no fixed size limit, so it can expand as long as memory is available. ▪ More flexible but involves additional memory overhead due to pointer storage. Properties of Stack: Fixed vs. Dynamic Size

▪ Contiguous Memory Allocation (Array-based Stack): ▪Memory is allocated in a single, continuous block. ▪Fast access due to direct indexing. ▪Limited flexibility because size is fixed at allocation time. ▪ Non-Contiguous Memory Allocation (Linked List-based Stack): ▪Memory is dynamically allocated node by node. ▪No predefined size limit. ▪Extra memory is used for pointers, leading to additional overhead. Properties of Stack: Memory Allocation

Array Implementation of Stack

▪ Analysis: ▪Suppose the stack has the following structure. Int num[Max-Size] ▪We need to have an integer variable that stores an index value that tells us: 1.The position where to store a new value 2.The total number of elements stored in the stack Int top =- 1 ; ▪ To push/add an element to the stack ▪ Check if there is enough space in the stack (To add new value, we should have to check the space left) Top<Max_size- 1? Yes – increment top , store the element in Num[top] No – stack overflow

▪ To push/add an element to the stack

int arr[max_size]; int top=-1; void push(int x){ if (top<max_size- 1 ) { top++; arr[top]=x; } else cout<<“stack overflow”; }

Array Implementation of Stack

Applications of Stack

▪ When are stacks useful?

▪A stack is widely used in computer science and real-life applications. Stacks play a fundamental role in parsing, evaluating, and converting algebraic expressions.

1. Function Call Management in Recursion ▪One common application is in writing compilers. Whenever a function call is made (or itself, in recursion), the code generated by the compiler must store the values of all local variables ready for when program execution returns from the function call. ▪Within the called function, any number of nested function calls could be made, and for each of them the values of local variables (the environment) also needs to be stored. ▪ A stack is an ideal data structure for this task. Before each function call, the current environment is pushed onto a stack, and as each function finishes execution, the environment is popped from the stack.

1. Function Call Management in Recursion ▪Consider the following code:

Applications of Stack

2. Undo/Redo Operations ▪Applications like Microsoft Word, Photoshop , and text editors maintain a stack of actions. ▪ Undo operation pops the last action from the stack. ▪ Redo operation pushes the undone action back onto the stack. 3. Browser History (Back and Forward Buttons) ▪When a user navigates a website, pages are stored in a stack. ▪Clicking " Back " pops the last page. ▪Clicking " Forward " restores the popped page. 4. Balancing Parentheses & Syntax Checking ▪Stacks are used to check balanced brackets in expressions. ▪Example: {[()]} - > Balanced ▪Example: {[(])} - > Not Balanced

Applications of Stack

5. Evaluation of Algebraic Expressions ▪Algebraic expressions can be written in three notations: 1. Infix: Operator between operands (e.g., A + B). 2. Postfix (RPN): Operator after operands (e.g., A B +). 3. Prefix (Polish): Operator before operands (e.g., + A B). ▪Stacks are used to: ▪ Evaluate postfix expressions (easiest, no parentheses needed). ▪ Convert infix to postfix/prefix (handles operator precedence and parentheses).

Applications of Stack

5. Evaluation of Algebraic Expressions: Postfix (Reverse Polish Notation) Evaluation ▪ Example: Evaluating 3 4 + 5 * Step-by-step Execution Final Answer = 35

Applications of Stack

Step Stack Operation

1. Push 3 [3] -

2. Push 4 [3, 4] -

3. + (Pop 3, 4, add) [7] 3 + 4

4. Push 5 [7, 5] -

5. * (Pop 7, 5, multiply) [35] 7 * 5 = 35

5. Evaluation of Algebraic Expressions: Infix to Postfix Conversion Algorithm (Shunting-Yard) 1.Initialize an empty stack (for operators) and a postfix string. 2.Scan the infix expression left to right: ▪ If operand → append to postfix. ▪ If ( → push to stack. ▪ If ) → pop and append until ( is found. ▪ If operator → pop higher/equal precedence operators first, then push current operator. 3.Pop all remaining operators.

Applications of Stack