0% found this document useful (0 votes)
34 views

Data STR Chapter 4

A stack is a linear data structure that follows LIFO principles. It can be implemented using arrays or linked lists. Key operations on a stack include push, pop and peek. Push adds an element to the top, pop removes from the top, and peek returns the top element without removing.

Uploaded by

kasutaye192
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Data STR Chapter 4

A stack is a linear data structure that follows LIFO principles. It can be implemented using arrays or linked lists. Key operations on a stack include push, pop and peek. Push adds an element to the top, pop removes from the top, and peek returns the top element without removing.

Uploaded by

kasutaye192
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter 4: Stacks

A stack is an Abstract Data Type (ADT), that is popularly used in most programming languages.
It is named stack because it has the similar operations as the real-world stacks, for example – a
pack of cards or a pile of plates, etc.
The stack follows the LIFO (Last in - First out) structure where the last element inserted would
be the first element deleted.

Properties of Stack
A Stack is a linear data structure that holds a linear, ordered sequence of elements. It is an
abstract data type. A Stack works on the LIFO process (Last In First Out), i.e., the element that
was inserted last will be removed first. To implement the Stack, it is required to maintain a
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.
A stack is a widely used data structure with unique characteristics which differentiate it from
other data structures. Below are its key features:

 A stack follows the LIFO principle: Last In, First Out -- the last inserted element will be
the first to get removed.
 Insertion and deletion are allowed at one end only, i.e., the 'top' of the stack.
 The 'base' of the stack points to the first inserted element in the stack and the 'top' of the
stack points to the last inserted element.

Operation on Stack

Prepared by: Eyoas A. Page 1


1. PUSH: PUSH operation implies the insertion of a new element into a Stack. A new element is
always inserted from the topmost position of the Stack; thus, we always need to check if the top
is empty or not, i.e., TOP=Max-1 if this condition goes false, it means the Stack is full, and no
more elements can be inserted, and even if we try to insert the element, a Stack overflow
message will be displayed.
Algorithm:
Step-1: If TOP = Max-1
Print “Overflow”
Goto Step 4
Step-2: Set TOP= TOP + 1
Step-3: Set Stack[TOP]= ELEMENT
Step-4: END

2. POP: POP means to delete an element from the Stack. Before deleting an element, make sure
to check if the Stack Top is NULL, i.e., TOP=NULL. If this condition goes true, it means the
Stack is empty, and no deletion operation can be performed, and even if we try to delete, then the
Stack underflow message will be generated.
Algorithm:
Step-1: If TOP= NULL
Print “Underflow”
Goto Step 4
Step-2: Set VAL= Stack[TOP]
Step-3: Set TOP= TOP-1
Step-4: END

3. PEEK: When we need to return the value of the topmost element of the Stack without deleting
it from the Stack, the Peek operation is used. This operation first checks if the Stack is empty,
i.e., TOP = NULL; if it is so, then an appropriate message will display, else the value will return.
Algorithm:
Step-1: If TOP = NULL
PRINT “Stack is Empty”
Goto Step 3
Step-2: Return Stack[TOP]
Step-3: END

Implementation of Stack
There are two ways to implement a stack –
 Using array
 Using linked list

Array Implementation of Stack

 When we implement stack uisng array we take the direction of the stack i.e the direction
in which elements are inserted towards right.

Prepared by: Eyoas A. Page 2


 Operations:
1. isempty() - to check if the Stack is empty or not.
2. push() - to insert element in the Stack.
3. pop() - to delete element from stack.
4. show_top() - to display element at top.
 Lets take an example of an array of 5 elements to implement stack. So we define the size
of the array using pre-processor directive #deifne SIZE 5 & then we can create an array
of 5 elements as int A[SIZE]; Also we will declare a top variable to track the element at
the top of the stack which will initially be -1 when the stack is empty i.e int top=-1;

 isempty()- Now that we know that the stack is empty when top is equal to -1 we can use
this to implement our isempty() function i.e. when top == -1 retrun true else return false.
 push()- To push an element into the stack we will simply increment top by one and insert
the element at that position. While inserting we have to take care of the condition when
the array is full i.e. when top == SIZE-1;
 pop()- To pop an element from the stack we will simple decrement top by one which will
simply mean that the element is no longer the part of the stack. In this case we have to
take care of the condition when the stack is empty i.e top == -1 then we cannot perform
the pop operation.
 show_top()- we will simply print the element at top if the stack is not empty.
 Lets say we have an stack with one element i.e 2 and we have to insert ot push an element
3 to this stack.

Prepared by: Eyoas A. Page 3


 then we will simply increment top by one and push the element at top.

 And to pop an element we will simply decrement top by one.

Implementation using C++


#include <iostream>
using namespace std;
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;

Prepared by: Eyoas A. Page 4


else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}

Prepared by: Eyoas A. Page 5


}while(ch!=4);
return 0;
}

Output
1) Push in stack
2) Pop from stack
3) Display stack
4) Exit

Enter choice: 1
Enter value to be pushed: 2
Enter choice: 1
Enter value to be pushed: 6
Enter choice: 1
Enter value to be pushed: 8
Enter choice: 1
Enter value to be pushed: 7
Enter choice: 2
The popped element is 7
Enter choice: 3
Stack elements are:8 6 2
Enter choice: 5
Invalid Choice
Enter choice: 4
Exit

In the above program, the push() function takes argument val i.e., value to be

pushed into the stack. If a top is greater than or equal to n, there is no space in

a stack and overflow is printed. Otherwise, val is pushed into the stack. The code snippet for this
is as follows.
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}

The pop() function pops the topmost value of the stack, if there is any value. If

the stack is empty then underflow is printed. This is given as follows.

Prepared by: Eyoas A. Page 6


void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}

The display() function displays all the elements in the stack. It uses a for loop to do so. If there
are no elements in the stack, then Stack is empty is printed. This is given below.
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
}else
cout<<"Stack is empty";
}

The function main() provides a choice to the user if they want to push, pop or display the stack.
According to the user response, the appropriate function is called using switch. If the user enters
an invalid response, then that is printed. The code snippet for this is given below.
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();

Prepared by: Eyoas A. Page 7


break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}

Linked List Implementation of Stack


When implementing a stack using singly linked list, it is essential to consider the standard
operations of push, pop, and peek. The push operation involves adding an element to the top of
the stack, while the pop operation removes the top element from the stack. The peek operation
returns the value of the top element without removing it.
Implementation using C++
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *next;
};
struct Node* top = NULL;
void push(int val) {
struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
newnode->data = val;
newnode->next = top;
top = newnode;
}
void pop() {
if(top==NULL)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< top->data <<endl;
top = top->next;
}
}
void display() {
struct Node* ptr;
if(top==NULL)
cout<<"stack is empty";
else {

Prepared by: Eyoas A. Page 8


ptr = top;
cout<<"Stack elements are: ";
while (ptr != NULL) {
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}
cout<<endl;
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}

Prepared by: Eyoas A. Page 9


Output
1) Push in stack
2) Pop from stack
3) Display stack
4) Exit

Enter choice: 1
Enter value to be pushed: 2
Enter choice: 1
Enter value to be pushed: 6
Enter choice: 1
Enter value to be pushed: 8
Enter choice: 1
Enter value to be pushed: 7
Enter choice: 2
The popped element is 7
Enter choice: 3
Stack elements are:8 6 2
Enter choice: 5
Invalid Choice
Enter choice: 4
Exit

In the above program, the structure Node is used to create the linked list that is implemented as
a stack. The code is given below.
struct Node {
int data;
struct Node *next;
};

The push() function takes argument val i.e., value to be pushed into the stack.

Then a new node is created and val is inserted into the data part. This node is added to the front
of the linked list and top points to it. The code snippet for this is as follows.
void push(int val) {
struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
newnode->data = val;
newnode->next = top;
top = newnode;
}

The pop() function pops the topmost value of the stack, if there is any value. If the stack is empty
then underflow is printed. This is given as follows.
void pop() {
if(top==NULL)
cout<<"Stack Underflow"<<endl;

Prepared by: Eyoas A. Page 10


else {
cout<<"The popped element is "<< top->data <<endl;
top = top->next;
}
}

The display() function displays all the elements in the stack. This is done by using ptr that
initially points to top but goes till the end of the stack. All the

data values corresponding ptr are printed. This is given below.


void display() {
struct Node* ptr;
if(top==NULL)
cout<<"stack is empty";
else {
ptr = top;
cout<<"Stack elements are: ";
while (ptr != NULL) {
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}
cout<<endl;
}

The function main() provides a choice to the user if they want to push, pop or

display the stack. According to the user response, the appropriate function is called using switch.
If the user enters an invalid response, then that is printed. The code snippet for this is given
below.
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}

Prepared by: Eyoas A. Page 11


case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}

Application of Stack

1. A Stack can be used for evaluating expressions consisting of operands and operators.
2. Stacks can be used for Backtracking, i.e., to check parenthesis matching in an expression.
3. It can also be used to convert one form of expression to another form.
4. It can be used for systematic Memory Management.

Advantages of Stack

1. A Stack helps to manage the data in the ‘Last in First out’ method.
2. When the variable is not used outside the function in any program, the Stack can be used.
3. It allows you to control and handle memory allocation and deallocation.
4. It helps to automatically clean up the objects.

Disadvantages of Stack

1. It is difficult in Stack to create many objects as it increases the risk of the Stack overflow.
2. It has very limited memory.
3. In Stack, random access is not possible.

4.4.2. Infix and Post fix (RPN) conversion

What is Infix Notation?

Infix notation is a method of writing mathematical expressions where the operators are placed
between the operands. It is the most commonly used notation in mathematics and everyday

Prepared by: Eyoas A. Page 12


arithmetic. For example, the expression "2 + 3" is written in infix notation, where the plus sign
(+) is placed between the operands 2 and 3.

Syntax of Infix Notation

The syntax of infix notation is X op Y.

What is Postfix Expression?

The kind of notation known as Postfix Expression, also referred to as Reverse Polish Notation,
places the operator after the operand. For instance, if the infix expression is x + y, the postfix
notation for that expression is x y +. The process of converting infix to postfix expressions will
be thoroughly covered.

Since postfix expressions are simpler to evaluate and without overhead brackets, they are seen as
superior than infix expressions.

Conversion of Infix to Postfix

Understanding how to switch between different notations is crucial. We will walk through the
process of changing from infix to postfix in this section. For the conversion described above, a
stack data structure will be used. We can transform expressions that contain operators, operands,
and brackets (‘(‘). All of these will be taken into account when converting the expression.

Rules for the Conversion from Infix to Postfix Expression

We are initially given an infix expression to translate into postfix notation. After being parsed
from left to right, the infix notation is changed to postfix. Assuming the postfix expression is
initially empty, the following steps will be used to fill it out:

 Initialize an empty stack and an empty string for the postfix expression.
 Scan the infix expression from left to right.
 If the scanned character is an operand (number or variable), append it to the postfix string.
 If the scanned character is an open parenthesis ‘(‘, push it onto the stack.
 If the scanned character is an operator (+, -, *, /, etc.), do the following:
 a. While the stack is not empty and the top of the stack is an operator with higher or equal
precedence to the current operator, pop operators from the stack and append them to the postfix
string.
 b. Push the current operator onto the stack.
 If the scanned character is a close parenthesis ‘)’, do the following:
 a. Pop operators from the stack and append them to the postfix string until an open parenthesis is
encountered (and discard the open parenthesis).
 Repeat steps 3-6 until all characters in the infix expression have been scanned.
 Pop any remaining operators from the stack and append them to the postfix string.
 The resulting string in the postfix notation is the desired output.

Infix Expression:

Prepared by: Eyoas A. Page 13


K + L - M*N + (O^P) * W/U/V * T + Q

Let’s perform a dry run of the aforementioned infix expression to determine the appropriate
postfix expression.
Left to right parsing is used for the string above. The table below shows, for each token, the
elements in the stack and the corresponding postfix expression up to that point:

Element Stack contents Postfix Expression

K K

+ +

L + KL

– – KL+

M – KL+M

* -* KL+M

N -* KL+MN

+ + KL+MN*–

( +( KL+MN*–

O +(^ KL+MN*–O

^ +(^ KL+MN*–O

P +(^ KL+MN*–OP

) + KL+MN*–OP^

* +* K L + M N* – O P ^

Prepared by: Eyoas A. Page 14


Element Stack contents Postfix Expression

W +* K L + M N* – O P ^ W

/ +/ K L + M N* – O P ^ W *

U +/ K L + M N* – O P ^W * U

/ +/ K L + M N* – O P ^W * U /

V +/ K L + M N* – O P ^ W * U / V

* +* K L + M N* – O P ^W * U / V /

T +* K L + M N* – O P ^W * U / V / T

+ + K L + M N* – O P ^W * U / V / T * +

Q + K L + M N* – O P ^W * U / V / T * + Q

K L + M N* – O P ^W * U / V / T * + Q+

The final postfix expression is


KL+MN∗−OPW∗U/V/T∗+Q+
Convert Postfix to Infix Expression
Objective: Given a Postfix expression, write an algorithm to convert it into Infix expression.
Example:
Input: Postfix expression: A B +
Output: Infix expression- (A + B)

Input: Postfix expression: ABC/-AK/L-*


Output: Infix expression: ((A-(B/C))*((A/K)-L))
Approach: Use Stack
Algorithm:
Iterate the given expression from left to right, one character at a time
1. If a character is operand, push it to stack.
2. If a character is an operator,
1. pop operand from the stack, say it's s1.
2. pop operand from the stack, say it's s2.

Prepared by: Eyoas A. Page 15


3. perform (s2 operator s1) and push it to stack.
3. Once the expression iteration is completed, initialize the result string and pop out from
the stack and add it to the result.
4. Return the result.
Please walk through the example below for more understanding.

Prepared by: Eyoas A. Page 16

You might also like