Ds Practical No 1 - 5
Ds Practical No 1 - 5
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.
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");
}
}
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);
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
Example
Consider the following Expression...
Input and Output
Input:
Postfix expression: 53+62/*35*+
Output:
The result is: 39
Algorithm
postfixEvaluation(postfix)
#include<iostream>
#include<cmath>
#include<stack>
using namespace std;
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.
Postfix Expression
In postfix expression, operator is used after operands. We can say that "Operator follows the
Operands".
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 * + =
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)
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.
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.
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");
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.
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.
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.
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 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