A stack is a linear data structure that follows the LIFO Principle.
LIFO means = Last In First Out
A stack can be defined as a container in which insertion and deletion can be performed from the one end
known as the top of the stack.
This is a real-life example of a stack.
o push(): When we insert an element in a stack then the operation is known as a push. If
the stack is full then the overflow condition occurs.
o pop(): When we delete an element from the stack, the operation is known as a pop. If the
stack is empty means that no element exists in the stack, this state is known as an underflow state.
o isEmpty(): It determines whether the stack is empty or not.
o isFull(): It determines whether the stack is full or not.'
o peek(): It returns the element at the given position.
o count(): It returns the total number of elements available in a stack.
o change(): It changes the element at the given position.
o display(): It prints all the elements available in the stack.
o Step 1: Checks if the Stack is full
o Step 2: If the stack is full, Produce an error and exit.
o Step 3: If the stack is not full, increments top to point next empty space.
o Step 4: Adds data element to the stack location, where top is pointing.
o Step 5: Return success
begin procedure push: stack, data if stack is full return null endif top ← top + 1 stack[top] ← data end procedure
void push(int data) {
if(!isFull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Stack is full.\n");
}
}
Here we have used isFull() Function, Let's see what is isFull() function algorithm
begin procedure isfull if top equals to MAXSIZE return true else return false endif end procedure
bool isfull() {
if(top == MAXSIZE)
return true;
else
return false;
}
let's see whether my stack is empty or not 樂
begin procedure isempty if top less than 1 return true else return false endif end procedure
bool isempty() {
if(top == -1)
return true;
else
return false;
}
Now let's see the pop operation and it's an algorithm
o Step 1: Checks if the Stack is full
o Step 2: If the stack is empty, produces an error and exit
o Step 3: If the stack is not empty, accesses the data element at which top is pointing.
o Step 4: Decreases the value of top by 1.
o Step 5: Return success
begin procedure pop: stack if stack is empty return null endif data ← stack[top] top ← top - 1 return data end procedure
int pop(int data) {
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Stack is empty.\n");
}
}
Now if I want to know the top element or you can say peek element then ? 樂
Let's see
begin procedure peek return stack[top] end procedure
int peek() {
return stack[top];
}
0 Comments