Final Project Dsa
Final Project Dsa
PROGRAM
COMPILATIONS
CC 104-DATA STRUCTURES AND
ALGORITHM
Submitted by:
Submitted to:
March 2020
10 EXAMPLES OF LIST
PROGRAM
1. Turbo C++: Singly Linked List
#include <iostream.h>
#include <string.h>
struct SLinkList
{
int data;
SLinkList *next;
SLinkList();
SLinkList(int value);
int SLinkList::DeleteNext()
{
if(this->next == NULL)
return 0;
while(node != NULL)
{
cout << node->data;
cout << "\n";
node = node->next;
}
}
int main()
{
SLinkList *node1 = new SLinkList(1);
SLinkList *node2 = node1->InsertNext(2);
SLinkList *node3 = node2->InsertNext(3);
SLinkList *node4 = node3->InsertNext(4);
SLinkList *node5 = node4->InsertNext(5);
node1->Traverse();
node2->Traverse();
Reference:http://www.softwareandfinance.com/Turbo_CPP/Turbo_CPP_Singly_Linked
_List.html
Program Explanation
Filling elements and traversal in forward direction.
2. Turbo C++: Reverse singly linked list
#include <iostream.h>
struct SLinkList
{
int data;
SLinkList *next;
SLinkList();
SLinkList(int value);
int SLinkList::DeleteNext()
{
if(this->next == NULL)
return 0;
while(node != NULL)
{
cout << node->data;
cout << "\n";
node = node->next;
}
}
while(1)
{
SLinkList *p = head;
if(p->next == testnode)
break;
while(1)
{
int temp = p->data;
p->data = p->next->data;
p->next->data = temp;
p = p->next;
if(p->next == testnode)
{
testnode = p;
break;
}
}
}
return head;
}
while(cp != NULL)
{
SLinkList *next = cp->next;
cp->next = prev;
prev = cp;
cp = next;
}
head = prev;
return head;
}
int main()
{
SLinkList *head = new SLinkList(1);
SLinkList *p = head->InsertNext(2);
p = p->InsertNext(3);
p = p->InsertNext(4);
p = p->InsertNext(5);
p = p->InsertNext(6);
p = p->InsertNext(7);
p = p->InsertNext(8);
head->Traverse();
newhead->Traverse();
Reference:
http://www.softwareandfinance.com/Turbo_CPP/Turbo_CPP_Reverse_Singly_Linked_L
ist.html
Program Explanation
struct DLinkList
{
int data;
DLinkList *next;
DLinkList *prev;
DLinkList();
DLinkList(int value);
// Easy to handle
node->prev = this;
node->next = NULL; // already set in constructor
this->next = node;
}
else
{
// Insert in the middle
DLinkList *temp = this->next;
node->prev = this;
node->next = temp;
this->next = node;
temp->prev = node;
// temp->next does not have to be changed
}
return node;
}
while(node != NULL)
{
cout << node->data;
cout << "\n";
node = node->next;
}
}
int main()
{
DLinkList *node1 = new DLinkList(1);
DLinkList *node3 = node1->InsertNext(3);
DLinkList *node2 = node3->InsertPrev(2);
DLinkList *node5 = node3->InsertNext(5);
DLinkList *node4 = node5->InsertPrev(4);
node1->TraverseFront();
node5->TraverseBack();
Reference:
http://www.softwareandfinance.com/Turbo_CPP/Turbo_CPP_Doubly_Linked_List.html
Program Explanation
I have given here Turbo C++ sample code for doubly linked list, filling elements and
traversal in forward and backward direction. I have NOT given the code for deleting the
nodes. It is easy to implement by changing the insert functions.
4. Turbo C++: Singly Linked Circular List
#include <iostream.h>
struct SLinkCircularList
{
int data;
SLinkCircularList *next;
SLinkCircularList();
SLinkCircularList(int value);
node->next = this;
this->next = node;
}
else
{
// Insert in the middle
int SLinkCircularList::DeleteNext()
{
if(this->next == this)
{
cout << "\nThe node can not be deleted as there is only one node in the
circular list\n";
return 0;
}
do
{
cout << node->data;
cout << "\n";
node = node->next;
}
while(node != startnode);
}
int count = 0;
SLinkCircularList *startnode = node;
do
{
count++;
node = node->next;
}
while(node != startnode);
return count;
}
int main()
{
SLinkCircularList *node1 = new SLinkCircularList(1);
node1->DeleteNext(); // Delete will fail in this case.
node1->GetNumberOfNodes();
node3->GetNumberOfNodes();
node5->GetNumberOfNodes();
node1->Traverse();
node3->DeleteNext(); // delete the node "FOUR"
node2->Traverse();
cout << "\n";
node1->GetNumberOfNodes();
node3->GetNumberOfNodes();
node5->GetNumberOfNodes();
cout << "\n";
return 0;
}
Reference:
http://www.softwareandfinance.com/Turbo_CPP/Turbo_CPP_Singly_Circular_List.html
Program Explanation
The main difference between singly linked list and singly linked circular list are the next
node pointer of last node is NULL in case of singly linked list where as next node pointer
of last node is first node in case of singly linked circular list.
5. Turbo C++: Program to Search for an Element
in the Linked List using Recursion
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
int main()
{
struct node *head;
int key, num;
Program Explanation
This C Program uses recursive function & search for an element in a linked list. A linked
list is an ordered set of data elements, each containing a link to its successor.
6. Turbo C++: Program to Search for an Element
in the Linked List without using Recursion
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
int main()
{
struct node *head = NULL;
int key, num;
return 0;
}
Reference:https://www.sanfoundry.com/c-program-search-linked-list-without-recursion/
Program Explanation
This C program, using iteration, searches for an element in a linked list. A linked list is
an ordered set of data elements, each containing a link to its successor.
7. Turbo C++: Program to Display the Nodes of a
Linked List in Reverse using Recursion
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
//Driver Function
int main ()
{
struct node *head = NULL;
insert_new_node (&head, 1);
insert_new_node (&head, 2);
insert_new_node (&head, 3);
insert_new_node (&head, 4);
printf ("LinkedList : ");
print (head);
printf ("\nLinkedList in reverse order : ");
print_reverse_recursive (head);
printf ("\n");
return 0;
}
//Recursive Reverse
void print_reverse_recursive (struct node *head)
{
if (head == NULL)
{
return;
}
Program Explanation
This C Program uses recursive function & reverses the nodes in a linked list and
displays the list. A linked list is an ordered set of data elements, each containing a link
to its successor. This program makes each data element to link to its predecessor.
8. Turbo C++: Program to Display all the Nodes
in a Linked List using Recursion
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
int main()
{
struct node *head = NULL;
generate(&head);
display(head);
delete(&head);
return 0;
}
Program Explanation
This C Program uses recursive function & displays a linked list. A linked list is an
ordered set of data elements, each containing a link to its successor.
9. Turbo C++: Program to Display all the Nodes
in a Linked List without using Recursion
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
int main()
{
struct node *head = NULL;
generate(&head);
display(head);
delete(&head);
return 0;
}
Program Explanation
This C program, using iteration, displays a linked list. A linked list is an ordered set of
data elements, each containing a link to its successor.
10. Turbo C++: Program to Print the Alternate
Nodes in a Linked List without using
Recursion
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
int main()
{
struct node *head = NULL;
generate(&head);
printf("\nDisplaying the alternate nodes\n");
display(head);
delete(&head);
return 0;
}
while(head != NULL)
{
if (!(flag % 2))
{
printf("%d ", head->a);
}
flag++;
head = head->next;
}
}
Program Explanation
This C program, using iteration, displays the alternate nodes in a linked list.A linked list
is an ordered set of data elements, each containing a link to its successor.
10 EXAMPLES OF ARRAY
PROGRAM
1. C Program to Calculate Sum & Average of an
Array
#include <stdio.h>
int main()
{
int i, num;
float total = 0.0, average;
printf ("Enter the value of N \n");
scanf("%d", &num);
int array[num];
/* Summation starts */
}
Reference: https://www.sanfoundry.com/c-program-sum-average-array/
Program Explanation
From users, take a number N as input, which will indicate the number of elements in the
array.
1. Create an array of integer of user-defined size.
2. Iterating through for loops (from [0 to N)), take integers as input from the user and
print them. These inputs are the elements of the array.
Now, start summation by iterating through all the elements and adding numbers
to calculate and print sum as well as to calculate average.
To calculate the average, the overall sum is divided by the total number of
elements in the array.
3. Print the average calculated.
2. C Program to Calculate the Sum of the Array
Elements using Pointer
#include <stdio.h>
#include <malloc.h>
void main()
{
int i, n, sum = 0;
int *a;
Reference: https://www.sanfoundry.com/c-program-sum-array-elements-using-pointer/
Program Explanation
void main()
{
static int array[5] = { 200, 400, 600, 800, 1000 };
int sum;
}
Reference: https://www.sanfoundry.com/c-program-sum-all-elements-array-using-
pointers/
Program Explanation
1. Declare a static array of some fixed size along with array element definition.
2. Take a variable sum, which will store the total sum of all the array elements.
3. Create a function with a single argument, in which we will pass the above created
array argument. This function will return the sum.
4. Inside this function, a for loop will run from 0 to array size-1, accessing each element
of array by adding the iterator i to the pointer variable (array argument, which was
passed to this function).
5. Elements will get add and the total sum will be returned from this function.
6. Variable sum inside main() function, will get this returned value and will be printed.
4. C Program to Compute the Sum of two One
Dimensional Arrays using Malloc
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
void main()
{
int i, n;
int *a, *b, *c;
int main()
{
int size,m=0,l=0;
for(int i=0;i<size;i++)
{
scanf("%d",&array[i]);
int largest=array[0];
for(int i=0;i<size;i++)
{
int sum=0;
for(int j=i;j<size;j++)
{
sum=sum+array[j];
if(sum>largest)
{
m=i;l=j;
largest=sum;
}
}
}
Declare a variable (n), in which the size of the array(s) will be stored.
2. Declare 3 pointer variables of integer type, to hold starting address of 3 different
arrays (a, b and c).
3. Using for loop running from 0 to arraySize-1, go at every location by adding the value
of integer i(the iterator)to the starting address of the array(s) and then take the input by
storing values to those locations.
4. Do the previous step for 2 arrays (i.e a and b).
5. Now, again using for loop, adding the value of i to the starting address of both the
arrays (a and b), extract each element from both the arrays holdd by a and b, add the
elements and store the result in third array (i.e c).
6. Print the elements of array c.
6. C Program to Put Even & Odd Elements of an
Array in 2 Separate Arrays
#include <stdio.h>
void main()
{
}
Reference: https://www.sanfoundry.com/c-program-even-odd-elements-2-separate-
arrays/
Program Explanation
1. Create three integer arrays namely ARR, OAR, EAR of some fixed capacity, 10.
2. Take size of the array as input from users and define the first array, ARR by
inserting elements of the array.
3. Using for loop, scan each and every element of the first array, check whether
they are even or odd by taking modulo of 2 on those numbers.
4. If the array element modulo 2, returns 0, this means the number is divisible by
2 and it is an even number. Add this number to second array.
5. If the array element modulo 2, returns 1, this means the number is not divisible
by 2 and it is an odd number. Add this number to third array.
6. Repeat steps 4 and 5 until all the elements of first array are checked.
7. At last, we will be having arrays second third holding all the even and odd
elements of first array respectively.
8. Print both the OAR AND EAR.
9. Exit.
7. C Program to Insert an Element in a Specified
Position in a given Array
#include <stdio.h>
void main()
{
int array[10];
int i, j, n, m, temp, key, pos;
array[pos] = key;
Program Explanation
if (found == 1)
{
for (i = pos; i < n - 1; i++)
{
vectorx[i] = vectorx[i + 1];
}
}
else
printf("Element %d is not found in the vector\n", element);
}
Reference: https://www.sanfoundry.com/c-program-delete-specified-integer-array/
Program Explanation
int i, n, number[30];
printf("Enter the value of the n = ");
scanf("%d", &n);
number[n] = number[0];
for (i = 0; i < n; ++i)
{
number[i] = number[i + 1];
}
}
Reference: https://www.sanfoundry.com/c-program-cyclically-permute-elements-array/
Program Explanation
1. Create an array of integer of some certain maximum capacity (10, in this case).
2. From users, take a number N as input, which will indicate the number of elements in
the array (N < = maximum capacity)
3. Iterating through for loops (from [0 to N) ), take integers as input from user and print
them. These input are the elements of the array.
4. Now assign the value of first element of the array at 0th position to the nth position of
the array.
5. Starting a for loop, with i as iterator from 0 to size-1, assigning each element at
(i+1)th position to ith position, hence each element shifts left by one.
6. And value of last element at (n-1)th position would be assigned a value at nth
position. Remember we stored the very first value of array at nth position.
10. C Program to Find the Biggest Number in
an Array of Numbers using Recursion
#include <stdio.h>
int large(int[], int, int);
int main()
{
int size;
int largest;
int list[20];
int i;
if (size == 0)
{
printf("Empty list\n");
}
else
{
largest = list[0];
largest = large(list, size - 1, largest);
printf("\nThe largest number in the list is: %d\n", largest);
}
if (position == 0)
return largest;
if (position > 0)
{
if (list[position] > largest)
{
largest = list[position];
}
return large(list, position - 1, largest);
}
Reference: https://www.sanfoundry.com/c-program-biggest-number-array-using-
recursion/
Program Explanation
1. Declare an array of some fixed capacity, 20 and take size from the users and define
elements in unsorted fashion using rand() functions to insert random number less than
size ( rand() % size )
2. Assume first element of the array to be the largest number.
2. Create a function with three parameters i.e the array, last index of array (size -1) and
largest element of the array.
4. Call this function.
5. Inside it, the largest number is compared with the element at position passed to the
function (initially the position passed is the last index of the array) and make necessary
updation if largest number is smaller than the number compared.
6. After comparison, this function is again called inside itself but with position being
previous position(last index)-1.
7. This way all elements are compared with largest number making updation wherever
needed via recursion.
8. This process stops when the variable position reaches the 0th position.
10 EXAMPLES OF STACKS
PROGRAM
1. C Program to Implement a Stack
#include <stdio.h>
#define MAXSIZE 5
struct stack
{
int stk[MAXSIZE];
int top;
};
typedef struct stack STACK;
STACK s;
void push(void);
int pop(void);
void display(void);
void main ()
{
int choice;
int option = 1;
s.top = -1;
1. Ask the user for the operation like push, pop, display and exit. Use the variable top to
represent the top of the stack.
2. According to the option entered, access its respective function using switch
statement.
3. In the function push(), firstly check if the stack is full. If it is, then print the output as
“Stack is Full”. Otherwise take the number to be inserted as input and store it in the
variable num. Copy the number to the array stk[] and increment the variable top by 1.
4. In the function pop(), firstly check if the stack is empty. If it is, then print the output as
“Stack is Empty”. Otherwise print the top most element of the array stk[] and decrement
the variable top by 1.
5. In the function display(), using for loop print all the elements of the array.
6. Exit.
2. C Program to Reverse a Stack using
Recursion
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
int main()
{
struct node *head = NULL;
generate(&head);
printf("\nThe sequence of contents in stack\n");
display(head);
printf("\nInversing the contents of the stack\n");
if (head != NULL)
{
stack_reverse(&head, &(head->next));
}
printf("\nThe contents in stack after reversal\n");
display(head);
delete(&head);
return 0;
}
if (*head_next != NULL)
{
temp = (*head_next)->next;
(*head_next)->next = (*head);
*head = *head_next;
*head_next = temp;
stack_reverse(head, head_next);
}
}
Program Explanation
This C program, using recursion, reverses a stack content. Stack here is represented
using a linked list. A linked list is an ordered set of data elements, each containing a link
to its successor.
3. C Program to Reverse a Stack without using
Recursion
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
int main()
{
struct node *head = NULL;
generate(&head);
printf("\nThe sequence of contents in stack\n");
display(head);
printf("\nInversing the contents of the stack\n");
stack_reverse(&head);
printf("\nThe contents in stack after reversal\n");
display(head);
delete(&head);
return 0;
}
if (*head == NULL)
{
printf("Stack does not exist\n");
}
else if ((*head)->next == NULL)
{
printf("Single node stack reversal brings no difference\n");
}
else if ((*head)->next->next == NULL)
{
(*head)->next->next = *head;
*head = (*head)->next;
(*head)->next->next = NULL;
}
else
{
prev = *head;
temp = (*head)->next;
*head = (*head)->next->next;
prev->next = NULL;
while ((*head)->next != NULL)
{
temp->next = prev;
prev = temp;
temp = *head;
*head = (*head)->next;
}
temp->next = prev;
(*head)->next = temp;
}
}
This C program, using iteration, reverses a stack content. Stack here is represented
using a linked list. A linked list is an ordered set of data elements, each containing a link
to its successor.
4. C Program to Implement two Stacks using a
Single Array & Check for Overflow &
Underflow
#include <stdio.h>
#define SIZE 10
int ar[SIZE];
int top1 = -1;
int top2 = SIZE;
int main()
{
int ar[SIZE];
int i;
int num_of_ele;
return 0;
}
Reference: https://www.sanfoundry.com/c-program-two-stacks-single-array/
Program Explanation
This C Program Implements two Stacks using a Single Array & Check for Overflow &
Underflow. A Stack is a linear data structure in which a data item is inserted and deleted
at one record. A stack is called a Last In First Out (LIFO) structure. Because the data
item inserted last is the data item deleted first from the stack.
To implement two stacks in one array, there can be two methods.
First is to divide the array in to two equal parts and then give one half two each stack.
But this method wastes space.
So a better way is to let the two stacks to push elements by comparing tops of each
other, and not up to one half of the array.
Push and Pop functions of both stack in the following code has their Time Complexity
as O(1). They take constant time.
Print is O(n), where n is the number of elements in the stack.
The program has an array of size 10. 6 values are pushed in stack 1 and 4 in two. All
conditions are being checked
5. C Program to Implement a Stack using Linked
List
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
if (top1 == NULL)
{
printf("Stack is empty");
return;
}
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
void main()
{
int i, choice;
char s[MAX], b;
while (1)
{
printf("1-enter string\n2-exit\n");
printf("enter your choice\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter the String\n");
scanf("%s", s);
for (i = 0;s[i] != '\0';i++)
{
b = s[i];
push(b);
}
for (i = 0;i < (strlen(s) / 2);i++)
{
if (stack[top] == stack[front])
{
pop();
front++;
}
else
{
printf("%s is not a palindrome\n", s);
break;
}
}
if ((strlen(s) / 2) = = front)
printf("%s is palindrome\n", s);
front = 0;
top = -1;
break;
case 2:
exit(0);
default:
printf("enter correct choice\n");
}
}
}
Program Explanation
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);
getch();
return 0;
}
Reference:
https://www.tutorialspoint.com/data_structures_algorithms/stack_program_in_c.htm
Program Explanation
If we compile and run the above program, it will produce a list of elements and the
program will determine whether the stack is full or not
8. C Program to Illustrate Stack Operations using
MACROS
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
#define EMPTY "Stack is Empty"
#define OVERFLOW "Stack Overflow"
#define ISOVERFLOW top >= MAX - 1 /*Macro to find whether the stack is full*/
#define ISEMPTY top == -1 /*Macro to find whether the stack is empty*/
void push(int);
void pop();
void display();
void stacksize();
void destroy();
void stackfull();
void main()
{
int choice, value;
while (1)
{
printf("Enter Your choice:\n");
printf("1.PUSH\n2.POP\n3.DISPLAY\n4.STACKSIZE\n5.DESTROY\n6.SATCKFULL
CHECK\n7.EXIT");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("enter the value to be pushed on to the stack");
scanf("%d", &value);
push(value);
continue;
case 2:
pop();
continue;
case 3:
display();
continue;
case 4:
stacksize();
continue;
case 5:
destroy();
continue;
case 6:
stackfull();
continue;
case 7:
exit(0);
default:
printf("YOU HAVE ENTERD A WRONG CHOICE");
}
}
}
void display()
{
int temp = top;
if (ISEMPTY)
{
printf(EMPTY);
return;
}
while (temp + 1)
{
printf("%d\n", stack[temp]);
temp--;
}
}
if (ISEMPTY)
{
printf(EMPTY);
return;
}
while (temp + 1)
{
printf("%d\n", stack[temp]);
temp--;
count++;
}
if (count >= MAX)
{
printf("Stack is full");
}
else
{
printf("there are %d more spaces in the stack", (MAX-count));
}
}
void destroy()
{
if (ISEMPTY)
{
printf("nothing is there to destroy");
}
while (top != -1)
{
pop();
}
}
Reference:https://www.sanfoundry.com/c-program-stack-operations-using-macros/
Program Explanation
1. Ask the user for the operations like push, pop, display etc.
2. According to the entered option access the respective functions. Use switch
statement to access the functions.
3. Use #define function to define macros as mentioned in the program.
4. In the push() function, ask the user to enter the number to be inserted and store the
value in the variable value and copy this value into the array stack[]. Use the variable
top to represent the top of the stack.
5. In the pop() function, delete the element at the top of the array and decrement the
variable top.
6. In the display() function, print all the elements from the top of stack to the bottom.
7. In the stack_size() function, print the number of elelments in the array stack.
8. In the destroy() function, pop all the elements from the array stack[].
9. In the stackfull() function, check if the array stack[] is full or not.
9. C Program to Implement Stack Operations
using Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *link;
}*top = NULL;
#define MAX 5
// function prototypes
void push();
void pop();
void empty();
void stack_full();
void stack_count();
void destroy();
void print_top();
void main()
{
int choice;
while (1)
{
printf("1. push an element \n");
printf("2. pop an element \n");
printf("3. check if stack is empty \n");
printf("4. check if stack is full \n");
printf("5. count/display elements present in stack \n");
printf("6. empty and destroy stack \n");
printf("7. Print top of the stack \n");
printf("8. exit \n");
printf("Enter your choice \n");
scanf("%d",&choice);
switch (choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
empty();
break;
case 4:
stack_full();
break;
case 5:
stack_count();
break;
case 6:
destroy();
break;
case 7:
print_top();
break;
case 8:
exit(0);
default:
printf("wrong choice\n");
}
}
}
count = st_count();
if (count <= MAX - 1)
{
printf("\nEnter value which you want to push into the stack :\n");
scanf("%d",&val);
temp->data = val;
temp->link = top;
top = temp;
}
else
printf("WARNING: STACK FULL\n");
}
count = st_count();
if (count = = MAX)
{
printf("stack is full\n");
}
else
printf("stack is not full \n");
}
// to count the number of elements
void stack_count()
{
int count = 0;
struct node *temp;
temp = top;
while (temp! = NULL)
{
printf(" %d\n",temp->data);
temp = temp->link;
count++;
}
printf("size of stack is %d \n",count);
}
int st_count()
{
int count = 0;
struct node *temp;
temp = top;
while (temp! = NULL)
{
temp = temp->link;
count++;
}
return count;
}
void main()
{
int i, choice;
char s[MAX], b;
while (1)
{
printf("1-enter string\n2-exit\n");
printf("enter your choice\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter the String\n");
scanf("%s", s);
for (i = 0;s[i] != '\0';i++)
{
b = s[i];
push(b);
}
for (i = 0;i < (strlen(s) / 2);i++)
{
if (stack[top] == stack[front])
{
pop();
front++;
}
else
{
printf("%s is not a palindrome\n", s);
break;
}
}
if ((strlen(s) / 2) = = front)
printf("%s is palindrome\n", s);
front = 0;
top = -1;
break;
case 2:
exit(0);
default:
printf("enter correct choice\n");
}
}
}
Program Explanation
1. Take a string as input and store it in the array s[].
2. Load each character of the array s[] into the array stack[].
3. Use variables front and top to represent the last and top element of the array stack[].
4. Using for loop compare the top and last element of the array stack[]. If they are equal,
then delete the top element, increment the variable front by 1 and compare again.
5. If they are not equal, then print the output as “It is not a palindrome”.
6. Compare the elements in the steps 4-5 upto the middle element of the array stack[].
7. If every characters of the array is equal, then it is a paliandrome.
10 EXAMPLES OF QUEUE
PROGRAM
1. C Program to Implement a Queue using an
Array
#include <stdio.h>
#define MAX 50
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */
void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /* End of insert() */
void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */
void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}
Reference: https://www.sanfoundry.com/c-program-queue-using-array/
Program Explanation
1. Ask the user for the operation like insert, delete, display and exit.
2. According to the option entered, access its respective function using switch
statement. Use the variables front and rear to represent the first and last element of the
queue.
3. In the function insert(), firstly check if the queue is full. If it is, then print the output as
“Queue Overflow”. Otherwise take the number to be inserted as input and store it in the
variable add_item. Copy the variable add_item to the array queue_array[] and
increment the variable rear by 1.
4. In the function delete(), firstly check if the queue is empty. If it is, then print the output
as “Queue Underflow”. Otherwise print the first element of the array queue_array[] and
decrement the variable front by 1.
5. In the function display(), using for loop print all the elements of the array starting from
front to rear.
6. Exit.
2. C Program to Implement Queue Data Structure
using Linked List
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;
int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
rear = temp;
}
count++;
}
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
This C Program implements queue using linked list. Queue is a particular kind of
abstract data type or collection in which the entities in the collection are kept in order
and the principal (or only) operations on the collection are the addition of entities to the
rear terminal position, known as enqueue, and removal of entities from the front terminal
position, known as dequeue. This makes the queue a First-In-First-Out (FIFO) data
structure. Linked list is a data structure consisting of a group of nodes which together
represent a sequence. Here we need to apply the application of linked list to perform
basic operations of queue.
3. C Program to Implement Priority Queue to
Add and Delete Elements
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
void insert_by_priority(int);
void delete_by_priority(int);
void create();
void check(int);
void display_pqueue();
int pri_que[MAX];
int front, rear;
void main()
{
int n, ch;
create();
while (1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter value to be inserted : ");
scanf("%d",&n);
insert_by_priority(n);
break;
case 2:
printf("\nEnter value to delete : ");
scanf("%d",&n);
delete_by_priority(n);
break;
case 3:
display_pqueue();
break;
case 4:
exit(0);
default:
printf("\nChoice is incorrect, Enter a correct choice");
}
}
}
pri_que[i] = -99;
rear--;
if (rear == -1)
front = -1;
return;
}
}
printf("\n%d not found in queue to delete", data);
}
front = 0;
}
Reference: https://www.sanfoundry.com/c-program-priority-queue/
Program Explanation
struct node
{
int data;
struct node *link;
}*front, *rear;
// function protypes
void insert();
void delete();
void queue_size();
void check();
void first_element();
void main()
{
int choice, value;
while(1)
{
printf("enter the choice \n");
printf("1 : create an empty queue \n2 : Insert element\n");
printf("3 : Dequeue an element \n4 : Check if empty\n");
printf("5. Get the first element of the queue\n");
printf("6. Get the number of entries in the queue\n");
printf("7. Exit\n");
scanf("%d", &choice);
switch (choice) // menu driven program
{
case 1:
printf("Empty queue is created with a capacity of %d\n", MAX);
break;
case 2:
insert();
break;
case 3:
delete();
break;
case 4:
check();
break;
case 5:
first_element();
break;
case 6:
queue_size();
break;
case 7:
exit(0);
default:
printf("wrong choice\n");
break;
}
}
}
temp = front;
if (front == NULL)
{
printf("queue is empty \n");
front = rear = NULL;
}
else
{
printf("deleted element is %d\n", front->data);
front = front->link;
free(temp);
}
}
temp = front;
int cnt = 0;
if (front == NULL)
{
printf(" queue empty \n");
}
while (temp)
{
printf("%d ", temp->data);
temp = temp->link;
cnt++;
}
printf("********* size of queue is %d ******** \n", cnt);
}
Reference: https://www.sanfoundry.com/c-program-implement-queue-functions/
Program Explanation
1. Ask the user for the operations like insert, delete, display etc.
2. According to the entered option access the respective functions. Use switch
statement to access the functions.
3. Use structure with a data and a pointer as the data module. Use malloc function to
assign the memory dynamically.
4. In the insert() function ask the user to enter the number to be inserted and store the
value into the new data module’s data.
5. In the delete() function delete the element at the front.
6. In the check() function, check if the queue is empty or not.
7. In the first_element() function, print the first element of the queue.
5. C Program to Implement Queue Functions
Using Arrays and Macros
#include <stdio.h>
#include<stdlib.h>
/* Macro Definition */
#define MAX 10
#define EMPTY "QUEUE EMPTY"
#define ISFULL rear >= MAX - 1
#define FULL "QUEUE FULL"
#define ISEMPTY rear == -1
/* Fucntion Prototypes */
void insert_rear();
void delete_front();
void display_queue();
void empty_queue();
void front_ele();
int queue_size();
void destroy();
void main()
{
int choice, n, flag = 0;
char ch;
do
{
printf("MENU\n");
printf("Enter 1 to INSERT an element in the queue\n");
printf("Enter 2 to DELETE an element in the queue\n");
printf("Enter 3 to DISPLAY the elements of the queue\n");
printf("Enter 4 to CHECK if the queue is EMPTY\n");
printf("Enter 5 to KNOW the FIRST element of the queue\n");
printf("Enter 6 to KNOW the queue SIZE\n");
printf("Enter 7 to Destroy the Queue\n");
printf("Enter 8 to EXIT the program\n");
printf("Enter your Choice:");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert_rear();
break;
case 2:
delete_front();
break;
case 3:
display_queue();
break;
case 4:
empty_queue();
break;
case 5:
front_ele();
break;
case 6:
n = queue_size();
printf("\nthe queue size is: %d", n);
break;
case 7:
destroy();
flag = 1;
break;
case 8:
exit(0);
break;
default:
printf("WRONG CHOICE\n");
}
printf("\nDo you want to continue:");
scanf(" %c", &ch);
} while(ch == 'y' || ch == 'Y');
if (flag == 0)
{
destroy();
}
}
if (ISFULL)
{
printf(FULL);
}
else
{
printf("\nEnter the value you want to insert in the queue:");
scanf("%d", &val);
rear++;
queue[rear] = val;
printf("\nElement successfully inserted in the queue");
}
}
if (ISEMPTY)
{
printf(EMPTY);
}
else
{
for (i = front;i <= rear;i++)
{
printf("%d->", queue[i]);
}
}
}
if (ISEMPTY)
{
printf(EMPTY);
}
else
{
for (i = front;i <= rear;i++)
{
count++;
}
}
return count;
}
if (ISEMPTY)
{
printf("EMPTY QUEUE CANNOT BE DESTROYED");
}
else
{
size = queue_size();
Program Explanation
1. Ask the user for the operations like insert, delete, display etc.
2. According to the entered option access the respective functions. Use switch
statement to access the functions.
3. Use #define function to define macros as mentioned in the program.
4. In the insert_rear() function, ask the user to enter the number to be inserted and store
the value in the variable val and copy this value into the array queue[]. Use the variable
rear and front to represent the last and first element of the queue.
5. In the delete_front() function, delete the first element of the array and increment the
variable front.
6. In the display_queue() function, print all the elements of the array queue.
7. In the front_ele() function, check for the first element of the array queue[].
8. In the empty_queue() function, check if the array queue[] is empty or not.
9. In the queuesize() function, check the size of the array queue[].
10. In the destroy() function, delete all the elements from the array queue[].
6. C Program to Implement Queues using Stacks
#include <stdio.h>
#include <stdlib.h>
void push1(int);
void push2(int);
int pop1();
int pop2();
void enqueue();
void dequeue();
void display();
void create();
void main()
{
int ch;
int pop2()
{
return(st2[top2--]);
}
void dequeue()
{
int i;
void display()
{
int i;
1. Ask the user for the operations like insert, delete and display.
2. According to the entered option access the respective function using switch
statement.
3. In the enqueue() function push the element into the array st1[].
4. In the dequeue () function, firstly transfer all the elements of the array st1[] into the
new array st2[]. Then the pop the first element of the new array.
5. In the display() function print all the elements of the st1[].
7. C program to implement queue using array/
linear implementation of queue
#include <stdio.h>
#define MAX 10
int QUEUE[MAX],front=-1,rear=-1;
int main()
{
int ele,choice;
while(1)
{
//clrscr();
printf("\nQUEUE Elements are :");
display_Q(QUEUE);
printf("\n\nEnter choice (1:Insert,2:Display,3:Remove,0:Exit):");
scanf("%d",&choice);
switch(choice)
{
case 0:
exit(1);
break;
case 1:
printf("Enter an element to insert:");
scanf("%d",&ele);
insert_in_Q(QUEUE,ele);
break;
case 2:
display_Q(QUEUE);
break;
case 3:
remove_from_Q(QUEUE);
break;
default:
printf("\nInvalid choice\n");
break;
}
} //end of while(1)
return 0;
}
Reference: https://www.includehelp.com/c-programs/c-program-data-structure-queue-
implementation-using-array.aspx
Program Explanation
The program ask the user to input a number based on the instruction on the program, if
you click “1” it will ask to input a number to insert in the queue, if you click “2” it will
display the queue number you have given, if you click “3” it will remove the queue
number you have input in the program and if you click “0” the program will be
terminated.
8. Queue Implementation using C programming
#include<stdio.h>
#define SIZE 5
void enQueue(int);
void deQueue();
void display();
int main()
{
//deQueue is not possible on empty queue
deQueue();
//enQueue 5 elements
enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);
display();
return 0;
void deQueue(){
if(front == -1)
printf("\nQueue is Empty!!");
else{
printf("\nDeleted : %d", items[front]);
front++;
if(front > rear)
front = rear = -1;
}
}
void display(){
if(rear == -1)
printf("\nQueue is Empty!!!");
else{
int i;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",items[i]);
}
}
Reference: https://www.programiz.com/dsa/queue
Program Explanation
Two pointers called FRONT and REAR are used to keep track of the first and last
elements in the queue.
When initializing the queue, we set the value of FRONT and REAR to -1.
On enqueing an element, we increase the value of REAR index and place the new
element in the position pointed to by REAR.
On dequeueing an element, we return the value pointed to by FRONT and increase
the FRONT index.
Before enqueing, we check if queue is already full.
Before dequeuing, we check if queue is already empty.
When enqueing the first element, we set the value of FRONT to 0.
When dequeing the last element, we reset the values of FRONT and REAR to -1.
9. Simple Queue Program
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main() {
int item, choice, i;
int arr_queue[MAX_SIZE];
int rear = 0;
int front = 0;
int exit = 1;
return 0;
}
Reference: https://www.c-lang.thiyagaraaj.com/data-structures/c-queue-
programs/simple-queue-program-in-c-programming
Program Explanation
In each of the cases, the customer or object at the front of the line was the first one to
enter, while at the end of the line is the last to have entered. Every time a customer
finishes paying for their items (or a person steps off the escalator, or the machine part is
removed from the assembly line, etc.) that object leaves the queue from the front. This
represents the queue ? dequeue? function. Every time another object or customer
enters the line to wait, they join the end of the line and represent the ? enqueue?
function. The queue ?size? function would return the length of the line, and the ?empty?
function would return true only if there was nothing in the line.
10. C Program for Hospital Queue
#include <stdio.h>
#include<stdlib.h>
#define MAX 50
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
int main()
{
int choice;
while (1)
{
printf("1.Insert element to queue n");
printf("2.Delete element from queue n");
printf("3.Display all elements of queue n");
printf("4.Quit n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice n");
}
}
}
void insert()
{
int item;
if(rear == MAX - 1)
printf("Queue Overflow n");
else
{
if(front== - 1)
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &item);
rear = rear + 1;
queue_array[rear] = item;
}
}
void delete()
{
if(front == - 1 || front > rear)
{
printf("Queue Underflow n");
return;
}
else
{
printf("Element deleted from queue is : %dn", queue_array[front]);
front = front + 1;
}
}
void display()
{
int i;
if(front == - 1)
printf("Queue is empty n");
else
{
printf("Queue is : n");
for(i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("n");
}
}
Reference:https://www.edureka.co/blog/queue-in-c/
Program Explanation
This code is a menu-driven implementation of a queue. First, define the size of MAX
variable to be 50. Then, the array called queue array is declared of size MAX. There are
three functions that are to be declared. The functions are, insert, display and delete
functions. A menu-driven main function is used. The user is asked to enter his choice
and call the appropriate function to perform the task.
There are 2 pointers, the front is at the front of the queue and rear is at the back of the
queue. We add elements from the back of the queue and remove them from the front of
the queue.
Moving on with this article on Queue In C,