0% found this document useful (0 votes)
97 views27 pages

Ds Practical No 1 - 5

The document discusses implementing stacks using arrays in C, including functions for pushing, popping, checking if empty or full, and peeking at the top element. It provides code for these stack operations and uses them in a program that pushes several values onto a stack, prints the top, and pops and prints all elements. The document also covers evaluating postfix expressions using a stack and converting infix to postfix notation.

Uploaded by

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

Ds Practical No 1 - 5

The document discusses implementing stacks using arrays in C, including functions for pushing, popping, checking if empty or full, and peeking at the top element. It provides code for these stack operations and uses them in a program that pushes several values onto a stack, prints the top, and pops and prints all elements. The document also covers evaluating postfix expressions using a stack and converting infix to postfix notation.

Uploaded by

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

1. Title: Write a program to implement a stack using arrays.

Aim: Study of stack using array


Theory:
Stack

In the pushdown stacks only two operations are allowed: push the item into the stack, and pop
the item out of the stack. A stack is a limited access data structure - elements can be added and
removed from the stack only at the top. push adds an item to the top of the stack, pop removes the
item from the top. A helpful analogy is to think of a stack of books; you can remove only the top
book, also you can add a new book on the top.

A list with the restriction that insertion and deletion can be performed only from one end(LIFO) ,
called top.Operations of stack—push() ,pop() ,top() ,isempty(), etc.

• Inserting an object - push

• removing an object – pop


C program for Stack using an array
#include <stdio.h>

int MAXSIZE = 8;
int stack[8];
int top = -1;

int isempty() {

if(top == -1)
return 1;
else
return 0;
}

int isfull() {

if(top == MAXSIZE)
return 1;
else
return 0;
}

int peek() {
return stack[top];
}

int pop() {
int data;

if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.\n");
}
}

int push(int data) {

if(!isfull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.\n");
}
}
int main() {
// push items on to the stack
push(3);
push(5);
push(9);
push(1);
push(12);
push(15);

printf("Element at top of the stack: %d\n" ,peek());


printf("Elements: \n");

// print stack data


while(!isempty()) {
int data = pop();
printf("%d\n",data);
}

printf("Stack full: %s\n" , isfull()?"true":"false");


printf("Stack empty: %s\n" , isempty()?"true":"false");

return 0;
}

Output:
Element at top of the stack: 15
Elements:
15
12
1
9
5
3
Stack full: false
Stack empty: true
2. Title : Write a program to evaluate a given postfix expression using stacks.
Aim: Study of converting mathematical Postfix Expression using stack
Theory:
A postfix expression is a collection of operators and operands in which the operator is
placed after the operands. That means, in a postfix expression the operator follows the operands.
Postfix Expression has following general structure...
Operand1 Operand2 Operator

Postfix Expression Evaluation using Stack Data Structure


A postfix expression can be evaluated using the Stack data structure. To evaluate a postfix
expression using Stack data structure we can use the following steps...
1. Read all the symbols one by one from left to right in the given Postfix Expression
2. If the reading symbol is operand, then push it on to the Stack.
3. If the reading symbol is operator (+ , - , * , / etc.,), then perform TWO pop operations and
store the two popped oparands in two different variables (operand1 and operand2). Then
perform reading symbol operation using operand1 and operand2 and push result back on to
the Stack.
4. Finally! perform a pop operation and display the popped value as final result.

Example
Consider the following Expression...
Input and Output
Input:
Postfix expression: 53+62/*35*+
Output:
The result is: 39

Algorithm
postfixEvaluation(postfix)

Input: Postfix expression to evaluate.


Output: Answer after evaluating postfix form.
Begin
for each character ch in the postfix expression, do
if ch is an operator ⨀ , then
a := pop first element from stack
b := pop second element from the stack
res := b ⨀ a
push res into the stack
else if ch is an operand, then
add ch into the stack
done
return element of stack top
End

C Program for Evaluation of Postfix Expression

#include<iostream>
#include<cmath>
#include<stack>
using namespace std;

float scanNum(char ch) {


int value;
value = ch;
return float(value-'0'); //return float from character
}

int isOperator(char ch) {


if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^')
return 1; //character is an operator
return -1; //not an operator
}

int isOperand(char ch) {


if(ch >= '0' && ch <= '9')
return 1; //character is an operand
return -1; //not an operand
}
float operation(int a, int b, char op) {
//Perform operation
if(op == '+')
return b+a;
else if(op == '-')
return b-a;
else if(op == '*')
return b*a;
else if(op == '/')
return b/a;
else if(op == '^')
return pow(b,a); //find b^a
else
return INT_MIN; //return negative infinity
}

float postfixEval(string postfix) {


int a, b;
stack<float> stk;
string::iterator it;

for(it=postfix.begin(); it!=postfix.end(); it++) {


//read elements and perform postfix evaluation
if(isOperator(*it) != -1) {
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
stk.push(operation(a, b, *it));
}else if(isOperand(*it) > 0) {
stk.push(scanNum(*it));
}
}
return stk.top();
}

main() {
string post = "53+62/*35*+";
cout << "The result is: "<<postfixEval(post);
}

Output
The result is: 39
3. Title: Write a program to convert a given infix expression to postfix form using stacks.
Aim: Study of converting mathematical Infix Expression to Postfix Expression using stack
Theory:
Infix Expression
In infix expression, operator is used in between the operands.

The general structure of an Infix expression is as follows...


Operand1 Operator Operand2

Postfix Expression
In postfix expression, operator is used after operands. We can say that "Operator follows the
Operands".

The general structure of Postfix expression is as follows...


Operand1 Operand2 Operator

Infix to Postfix Conversion


Any expression can be represented using three types of expressions (Infix, Postfix, and Prefix). We
can also convert one type of expression to another type of expression like .........
Infix to Postfix,
Infix to Prefix,
Postfix to Prefix and vice versa.

To convert any Infix expression into Postfix or Prefix expression we can use the following
procedure...
1. Find all the operators in the given Infix Expression.
2. Find the order of operators evaluated according to their Operator precedence.
3. Convert each operator into required type of expression (Postfix or Prefix) in the same order.

Example
Consider the following Infix Expression to be converted into Postfix Expression...

D =A+ B * C
 Step 1 - The Operators in the given Infix Expression : = , + , *
 Step 2 - The Order of Operators according to their preference : * , + , =
 Step 3 - Now, convert the first operator * ----- D = A + B C *
 Step 4 - Convert the next operator + ----- D = A BC* +
 Step 5 - Convert the next operator = ----- D ABC*+ =
Finally, given Infix Expression is converted into Postfix Expression as follows...

DAB C * + =

Infix to Postfix Conversion using Stack Data Structure


To convert Infix Expression into Postfix Expression using a stack data structure, We can use the
following steps...

1. Read all the symbols one by one from left to right in the given Infix Expression.
2. If the reading symbol is operand, then directly print it to the result (Output).
3. If the reading symbol is left parenthesis '(', then Push it on to the Stack.
4. If the reading symbol is right parenthesis ')', then Pop all the contents of stack until
respective left parenthesis is poped and print each poped symbol to the result.
5. If the reading symbol is operator (+ , - , * , / etc.,), then Push it on to the Stack. However,
first pop the operators which are already on the stack that have higher or equal precedence
than current operator and print them to the result.

Example
Consider the following Infix Expression...

(A+ B ) * ( C - D )
The given infix expression can be converted into postfix expression using Stack data Structure as
follows...
The final Postfix Expression is as follows...

AB + C D - *
Input and Output
Input:
The infix expression. x^y/(5*z)+2
Output:
Postfix Form Is: xy^5z*/2+

Algorithm
infixToPostfix(infix)

C Program for conversion of Infix to Postfix Expression


#include<iostream>
#include<stack>
#include<locale> //for function isalnum()
using namespace std;

int preced(char ch) {


if(ch == '+' || ch == '-') {
return 1; //Precedence of + or - is 1
}else if(ch == '*' || ch == '/') {
return 2; //Precedence of * or / is 2
}else if(ch == '^') {
return 3; //Precedence of ^ is 3
}else {
return 0;
}
}

string inToPost(string infix ) {


stack<char> stk;
stk.push('#'); //add some extra character to avoid underflow
string postfix = ""; //initially the postfix string is empty
string::iterator it;

for(it = infix.begin(); it!=infix.end(); it++) {


if(isalnum(char(*it)))
postfix += *it; //add to postfix when character is letter or number
else if(*it == '(')
stk.push('(');
else if(*it == '^')
stk.push('^');
else if(*it == ')') {
while(stk.top() != '#' && stk.top() != '(') {
postfix += stk.top(); //store and pop until ( has found
stk.pop();
}
stk.pop(); //remove the '(' from stack
}else {
if(preced(*it) > preced(stk.top()))
stk.push(*it); //push if precedence is high
else {
while(stk.top() != '#' && preced(*it) <= preced(stk.top())) {
postfix += stk.top(); //store and pop until higher precedence is found
stk.pop();
}
stk.push(*it);
}
}
}

while(stk.top() != '#') {
postfix += stk.top(); /store and pop until stack is not empty.
stk.pop();
}

return postfix;
}

int main() {
string infix = "x^y/(5*z)+2";
cout << "Postfix Form Is: " << inToPost(infix) << endl;
}

Output
Postfix Form Is: xy^5z*/2+
4. Title: Write a program to implement circular queue using arrays.
Aim: Study of Circular Queue using an array
Theory:
Circular Queue is also a linear data structure, which follows the principle of FIFO(First In First
Out), but instead of ending the queue at the last position, it again starts from the first position after
the last, hence making the queue behave like a circular data structure.

Basic features of Circular Queue

1. In case of a circular queue, head pointer will always point to the front of the queue, and tail
pointer will always point to the end of the queue.

2. Initially, the head and the tail pointers will be pointing to the same location, this would mean that
the queue is empty.

3. New data is always added to the location pointed by the tail pointer, and once the data is added,
tail pointer is incremented to point to the next available location.

4. In a circular queue, data is not actually removed from the queue. Only the head pointer is
incremented by one position when dequeue is executed. As the queue data is only the data between
head and tail, hence the data left outside is not a part of the queue anymore, hence removed.
5. The head and the tail pointer will get reinitialised to 0 every time they reach the end of the
queue.

6. Also, the head and the tail pointers can cross each other. In other words, head pointer can be
greater than the tail, this will happen when we dequeue the queue a couple of times and the tail
pointer gets reinitialised upon reaching the end of the queue.
Circular Queue using Array:
The circular queue is a linear data structure. It follows FIFO principle. In circular queue, the last
node is connected back to the first node to make a circle. Circular array list fallows the First In First
Out principle. Elements are added at the rear end and the elements are deleted at the front end of the
queue.

In the Code below there are four parts. First three function to implement three different operations
like Insert a node, delete a node and display the list. The Fourth part is the main function, in that
a do while loop is implemented to keep the user engaged and provide him the all the given choices,
according to the choice one of the three function get called.
The First function checks whether the queue is empty, rear is at last position of queue or Queue is
full. If the queue is not full it adds up the item.
The Second function checks whether the list is empty, full or it has only one item. If any node
exists, it will delete the node in FIFO order.
The Third function will simply print all the elements of the Queue if exist. If not, then it will say
Queue is Empty.
The Queue can hold only 5 items, for changing the capacity edit the second line.

C program to implement circular queue using array


# include<stdio.h>
# define MAX 5

int cqueue_arr[MAX];
int front = -1;
int rear = -1;

/*Begin of insert*/
void insert(int item)
{
if((front == 0 && rear == MAX-1) || (front == rear+1))
{
printf("Queue Overflow \n");
return;
}
if (front == -1) /*If queue is empty */
{
front = 0;
rear = 0;
}
else
{
if(rear == MAX-1) /*rear is at last position of queue */
rear = 0;
else
rear = rear+1;
}
cqueue_arr[rear] = item ;
}
/*End of insert*/

/*Begin of del*/
void del()
{
if (front == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",cqueue_arr[front]);
if(front == rear) /* queue has only one element */
{
front = -1;
rear=-1;
}
else
{
if(front == MAX-1)
front = 0;
else
front = front+1;
}
}
/*End of del() */

/*Begin of display*/
void display()
{
int front_pos = front,rear_pos = rear;
if(front == -1)
{
printf("Queue is empty\n");
return;
}
printf("Queue elements :\n");
if( front_pos <= rear_pos )
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
else
{
while(front_pos <= MAX-1)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
front_pos = 0;
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
}
printf("\n");
}
/*End of display*/

/*Begin of main*/
int main()
{
int choice,item;
do
{
printf("1.Insert\n");
printf("2.Delete\n");
printf("3.Display\n");
printf("4.Quit\n");

printf("Enter your choice : ");


scanf("%d",&choice);

switch(choice)
{
case 1 :
printf("Input the element for insertion in queue : ");
scanf("%d", &item);

insert(item);
break;
case 2 :
del();
break;
case 3:
display();
break;
case 4:
break;
default:
printf("Wrong choice\n");
}
}while(choice!=4);

return 0;
}
/*End of main*/

Output:
5. Title: Write a program to implement double ended queue (dequeue) using arrays.
Aim:Study of Double Ended Queue using an array.
Theory:
Double ended queue is a more generalized form of queue data structure which allows insertion and
removal of elements from both the ends, i.e , front and back.

Implementation of Double ended Queue


Here we will implement a double ended queue using a circular array. It will have the following
methods:

 push_back : inserts element at back


 push_front : inserts element at front
 pop_back : removes last element
 pop_front : removes first element
 get_back : returns last element
 get_front : returns first element
 empty : returns true if queue is empty
 full : returns true if queue is full

Insert Elements at Front


First we check if the queue is full. If its not full we insert an element at front end by following the
given conditions :

 If the queue is empty then intialize front and rear to 0. Both will point to the first element.

Else we decrement front and insert the element. Since we are using circular array, we have to keep
in mind that if front is equal to 0 then instead of decreasing it by 1 we make it equal to SIZE-1.
Insert Elements at back
Again we check if the queue is full. If its not full we insert an element at back by following the
given conditions:

 If the queue is empty then intialize front and rear to 0. Both will point to the first element.
 Else we increment rear and insert the element. Since we are using circular array, we have to
keep in mind that if rear is equal to SIZE-1 then instead of increasing it by 1 we make it
equal to 0.

Delete First Element


In order to do this, we first check if the queue is empty. If its not then delete the front element by
following the given conditions :

 If only one element is present we once again make front and rear equal to -1.
 Else we increment front. But we have to keep in mind that if front is equal to SIZE-1 then
instead of increasing it by 1 we make it equal to 0.
Delete Last
Element
Inorder to do this, we again first check if the queue is empty. If its not then we delete the last
element by following the given conditions :

 If only one element is present we make front and rear equal to -1.
 Else we decrement rear. But we have to keep in mind that if rear is equal to 0 then instead of
decreasing it by 1 we make it equal to SIZE-1.

Check if Queue is
empty
It can be simply checked by looking where front points to. If front is still intialized with -1, the
queue is empty.
Check if Queue is full
Since we are using circular array, we check for following conditions as shown in code to check if
queue is full.

Return First Element


If the queue is not empty then we simply return the value stored in the position which front points.

Return Last Element


If the queue is not empty then we simply return the value stored in the position which rear points.
C Program for Double Ended Queue using Array
#include<stdio.h>
#include<conio.h>
#define SIZE 100

void enQueue(int);
int deQueueFront();
int deQueueRear();
void enQueueRear(int);
void enQueueFront(int);
void display();

int queue[SIZE];
int rear = 0, front = 0;

int main()
{
char ch;
int choice1, choice2, value;
printf("\n******* Type of Double Ended Queue *******\n");
do
{
printf("\n1.Input-restricted deque \n");
printf("2.output-restricted deque \n");
printf("\nEnter your choice of Queue Type : ");
scanf("%d",&choice1);
switch(choice1)
{
case 1:
printf("\nSelect the Operation\n");
printf("1.Insert\n2.Delete from Rear\n3.Delete from Front\n4. Display");
do
{
printf("\nEnter your choice for the operation in c deque: ");
scanf("%d",&choice2);
switch(choice2)
{
case 1: enQueueRear(value);
display();
break;
case 2: value = deQueueRear();
printf("\nThe value deleted is %d",value);
display();
break;
case 3: value=deQueueFront();
printf("\nThe value deleted is %d",value);
display();
break;
case 4: display();
break;
default:printf("Wrong choice");
}
printf("\nDo you want to perform another operation (Y/N): ");
ch=getch();
}while(ch=='y'||ch=='Y');
getch();
break;

case 2 :
printf("\n---- Select the Operation ----\n");
printf("1. Insert at Rear\n2. Insert at Front\n3. Delete\n4. Display");
do
{
printf("\nEnter your choice for the operation: ");
scanf("%d",&choice2);
switch(choice2)
{
case 1: enQueueRear(value);
display();
break;
case 2: enQueueFront(value);
display();
break;
case 3: value = deQueueFront();
printf("\nThe value deleted is %d",value);
display();
break;
case 4: display();
break;
default:printf("Wrong choice");
}
printf("\nDo you want to perform another operation (Y/N): ");
ch=getch();
} while(ch=='y'||ch=='Y');
getch();
break ;
}
printf("\nDo you want to continue(y/n):");
ch=getch();
}while(ch=='y'||ch=='Y');
}
void enQueueRear(int value)
{
char ch;
if(front == SIZE/2)
{
printf("\nQueue is full!!! Insertion is not possible!!! ");
return;
}
do
{
printf("\nEnter the value to be inserted:");
scanf("%d",&value);
queue[front] = value;
front++;
printf("Do you want to continue insertion Y/N");
ch=getch();
}while(ch=='y');
}

void enQueueFront(int value)


{
char ch;
if(front==SIZE/2)
{
printf("\nQueue is full!!! Insertion is not possible!!!");
return;
}
do
{
printf("\nEnter the value to be inserted:");
scanf("%d",&value);
rear--;
queue[rear] = value;
printf("Do you want to continue insertion Y/N");
ch = getch();
}
while(ch == 'y');
}
int deQueueRear()
{
int deleted;
if(front == rear)
{
printf("\nQueue is Empty!!! Deletion is not possible!!!");
return 0;
}
front--;
deleted = queue[front+1];
return deleted;
}
int deQueueFront()
{
int deleted;
if(front == rear)
{
printf("\nQueue is Empty!!! Deletion is not possible!!!");
return 0;
}
rear++;
deleted = queue[rear-1];
return deleted;
}

void display()
{
int i;
if(front == rear)
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else{
printf("\nThe Queue elements are:");
for(i=rear; i < front; i++)
{
printf("%d\t ",queue[i]);
}
}
}

Output

You might also like