Int empty stack s return s.top 1 năm 2024

A stack is a linear data structure in which an element is inserted or deleted only from the top position. Stack is based on last in last out [LIFO] property i.e. element inserted first will be the last one to be deleted.

For example, assume a stack of plates kept in a rack. Now if someone wants to utilize a plate, he will pull the topmost plate kept in the rack. Also, if someone wants to add a washed plate in the rack, he will be only adding it to the top.

Let us consider a static implementation of stack which is implemented using an array. As arrays only stores similar type of elements, stack will also store homogenous elements. Figure below shows an array implementation of a stack. Assume name of the array is stack with maximum size [MaxSize] 5.

Insertion into stack [PUSH]

Initially the stack is empty and value of top is -1. When an element is inserted the value of top will be incremented by 1 and the element would be inserted at the array index specified by the top variable. Same process is followed when more elements are inserted into stack until the stack is completely full.

Overflow condition: When stack is completely full [i.e. TOP= MaxSize -1 ] and we try to insert more element onto stack then this condition is called overflow condition and no further element could be inserted now until any element is deleted.

Deletion from stack [POP]

Whenever any element is deleted from stack, it is always done from top position. Element pointed out by top variable is deleted [or left as it] and value of top is decremented by 1 until the stack is empty.

Underflow Condition: When a stack is empty [i.e. TOP= -1] and we try to delete more element from it, then this condition is called underflow condition.

Function for PUSH operation

void push [int data] { if [TOP == MaxSize -1] {

cout

Chủ Đề