XIIB-CS-DATA STRUCTURES(LINK LIST,STACK,QUEUE)


DATA STRUCTURES

 

A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.Different kinds of data structures are suited to different kinds of applications.

Types of data structure

There are two types of data structures

Linear data structure-Array,Linked list,Stack,Queue

Non-Linear data structue – Graph and Tree

 

Array-

 


 

 

An array of airplanes                                                       An array of bugs

 


 

 

 

 

 

An array of cards                                                                An array of characters

 

An array is a group of items that can be identified as similar because they are of the same nature.

Arrays come in two flavors: one dimensional and multi-dimensional arrays. Everyone of the pictures above represents a single dimensional array.

 

Declaring an Array

Like any other variable, the syntax of declaring an array is:

DataType ArrayName[dimension/order]

The array is first identified by its kind, which could be a char, an int, a float, etc; followed by its name that follows the C++ naming rules. The name is then followed by square brackets that specify the dimension of the array or its size.

Here are examples of declaring arrays:

               int age[12];
               float grade[100];
               double angle[360];

int Age[12]; declares a group or array of 12 values, each one being an integer.

float Grade[100]; declares an array of 100 floating-point values.

double Angle[360]; declares an array of double-precision numbers. There are 360 of these items in the group.

 

Initializing an Array

Just like any variable can be initialized, an array also can be initialized. To accomplish this, for a one-dimensional array, the syntax used is:

DataType ArrayName[dimension] = { element1, element2, …, elementn};

Here are examples of declaring an initializing arrays:

int number[12] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12};
double distance[5] = {44.14, 720.52, 96.08, 468.78, 6.28};
 

Processing the Elements of an Array

#include <iostream>
int main()
{
               double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};
               cout << "2nd member = " << distance[1] << endl;
               cout << "5th member = " << distance[4] << endl;
               return 0;
}

This would produce:

2nd member = 720.52
5th member = 6.28
 
Operations on Arrays
#include <iostream>
int main()
{
               // We know that we need a constant number of elements
               const int max = 10;
               int number[max];
               // We will calculate their sum
               int sum = 0;
               cout << "Please type 10 integers.\n";
               for( int i = 0; i < max; i++ )
               {
                               cout << "Number " << i + 1 << ": ";
                               cin >> number[i];
                               sum += number[i];
               }
               cout << "\n\nThe sum of these numbers is " << Sum << "\n\n";
               return 0;
}

 

Arrays and Functions

·         An array can be passed to a function as argument.

·         An array can also be returned by a function. To declare and define that a function takes an array as argument, declare the function as you would do for any regular function and, in its parentheses, specify that the argument is an array.Here is an example:

#include <iostream>
void DisplayTheArray(double member[5]);
int main()
{
               const int numberOfItems = 5;
               double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};
               return 0;
}
void DisplayTheArray(double member[5])
{
               for(int i = 0; i < 5; ++i)
                               cout << "\nDistance " << i + 1 << ": " << member[i];
               cout << endl;
}

You don't have to specify the dimension of the array. This means that you can leave the square brackets empty:

#include <iostream>
void DisplayTheArray(double member[]);
int main()
{
               const int NumberOfItems = 5;
               double distance[NumberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};
               return 0;
}
 
void DisplayTheArray(double member[ ])
{
               for(int i = 0; i < 5; ++i)
                               cout << "\nDistance " << i + 1 << ": " << member[i];
               cout << endl;
}

 

Practice :

 

 

 

#include <iostream>
 
void DisplayTheArray(double member[])
{
               for(int i = 0; i < 5; ++i)
                               cout << "\nDistance " << i + 1 << ": " << member[i];
               cout << endl;
}
 
int main()
{
               const int numberOfItems = 5;
               double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};
               cout << "Members of the array";
               DisplayTheArray(distance);
               return 0;
}

This would produce:

Members of the array
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
 
Practice :-#include <iostream>
void DisplayTheArray(double member[])
{
               for(int i = 0; i < 5; ++i)
                               cout << "\nDistance " << i + 1 << ": " << member[i];
               cout << endl;
}
 
int main()
{
               const int NumberOfItems = 5;
               double distance[NumberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};
               cout << "Members of the array";
               DisplayTheArray(distance[3]);
               return 0;
}
 
Practice:- #include <iostream>
 
void DisplayTheArray(double mbr[ ], int count);
int main()
{
               double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12};
               // Processing 5 members of the array
               cout << "Members of the array";
               DisplayTheArray(distance, 5);
               // Processing all members of the array
               int sizeOfArray = sizeof(Distance)/sizeof(double);
               cout << "\nMembers of the array";
               DisplayTheArray(distance, sizeOfArray);
               return 0;
}
 
void DisplayTheArray(double member[], int counter)
{
               for(int i = 0; i < counter; ++i)
                               cout << "\nDistance " << i + 1 << ": " << member[i];
               cout << endl;
}

This would produce:

Members of the array
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
Members of the array
 
Searching
 
Linear search: Linear search or sequential search is a method for finding a particular value in a list, that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found.
function for linear search
 
#include <iostream>
int LinearSearch(int Array[], const int Size, const int ValToSearch)
{              bool NotFound = true;
               int i = 0;
               while(i < Size && NotFound)
               {
                               if(ValToSearch != Array[i])
                                              i++;
                               else
                                              NotFound = false;
               }
               if( NotFound == false )
                               return i;
               else
                               return -1;
}
 
int main()
{
               int Number[] = { 67, 278, 463, 2, 4683, 812, 236, 38 };
               int Quantity = sizeof(Number) / sizeof(int);
               int NumberToSearch = 0;
               cout << "Enter the number to search: "; cin >> NumberToSearch;
               int i = LinearSearch(Number, Quantity, NumberToSearch);
               if(i == -1)
                               cout << NumberToSearch << " was not found in the collection\n\n";
               else
               {
                               cout << NumberToSearch << " is at the " << i+1;
 
                               if( i == 0 )
                                              cout<< "st position of the collection\n\n";
                               else if( i == 1 )
                                              cout<< "nd position of the collection\n\n";
                               else if( i == 2 )
                                              cout<< "rd position of the collection\n\n";
                               else
                                              cout<< "th position of the collection\n\n";
               }
               return 0;
}
 
Binary search
 
A binary search is an algorithm for locating the position of an element in a sorted array. It inspects the middle element of the sorted list: if equal to the sought value, then the position has been found; otherwise, the upper half or lower half is chosen for further searching based on whether the sought value is greater than or less than the middle element. The method reduces the number of elements needed to be checked by a factor of two each time, and finds the sought value if it exists in the list or if not determines "not present", in logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.
 
#include<iostream.h>
#include<conio.h>
void binsearch(int ar[],int size,int ele)
{       int lb=0,ub=size-1,mid;             //lb=>lower bound,ub=>upper bound
     for(;lb<ub;)
       {
           mid=(lb+ub)/2;
 
           if(ar[mid]==ele)
             {
                cout<<"\n SEARCH SUCCESSFUL";
                break;
             }
           else
                 if(ar[mid]<ele)
                 ub=mid-1;
          else
               if(ar[mid]>ele)
                  lb=mid+1;
      }
       if(ub<lb)
         cout<<"\n SEARCH UNSUCCESSFUL";
}
 
void sort(int ar[],int size)               //sorts the array in ascending array using bubble sort
{
     int temp;
     for(int i=0;i<size;i++)
         for(int j=0;j<size-i-1;j++)
          if(ar[j]>ar[j+1])
               {
                temp=ar[j];
                ar[j]=ar[j+1];
                ar[j+1]=temp;
               }
}
void display(int ar[],int size)
{
     for(int i=0;i<size;i++)
         cout<<'\n'<<ar[i];
}
void input(int ar[],int size)
{
     for(int i=0;i<size;i++)
         cin>>ar[i];
}
void main()
{
     clrscr();
     int size;
     cout<<"\n ENTER THE NUMBER OF ELEMENTS REQUIRED IN THE ARRAY :";
     cin>>size;
     int *ar=new int(size);
     cout<<"\n ENTER THE ELEMENTS OF THE ARRAY :\n";
     input(ar,size);         //takes the input from the array
     sort(ar,size);         //sorts the array in the ascending order
     int ele;
     cout<<"\n ENTER THE ELEMENT TO BE FOUND :\n";
     cin>>ele;
     getch();
}
 
Sorting
 
A sorting algorithm is an algorithm that puts elements of a list in a certain order
1.    Insertion sort is a simple sorting algorithm, a comparison sort in which the sorted array (or list) is built one entry at a time. 
 
#include <iostream>
#define ELEMENTS 6
void insertion_sort(int x[],int length)
{
  int key,i;
  for(int j=1;j<length;j++)
  {
     key=x[j];
     i=j-1;
     while(x[i]>key && i>=0)
     {
               x[i+1]=x[i];
         i--;
     }
     x[i+1]=key;
  }
}
 
int main()
{
  int A[ELEMENTS]={5,2,4,6,1,3};
  int x;
  cout<<"NON SORTED LIST:"<<endl;
  for(x=0;x<ELEMENTS;x++)
  {
       cout<<A[x]<<endl;
  }
  insertion_sort(A,ELEMENTS);
  cout<<endl<<"SORTED LIST"<<endl;
  for(x=0;x<ELEMENTS;x++)
  {
       cout<<A[x]<<endl;
  }
  return 0;
}
 
2.    Selection Sort
Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort
void SelectionSort(int A[], int length)
{
    int i, j, min, minat;
         for(i = 0; i<(length-1); i++)
         {
                         minat = i;
                         min = A[i];
 
      for(j = i+1;j < length; j++) //select the min of the rest of array
           {
                           if(min > A[j])   //ascending order for descending reverse
                           {
                                          minat = j;  //the position of the min element 
                                          min = A[j];
                           }
           }
           int temp = A[i];
           A[i] = A[minat];  //swap 
           A[minat]=temp;    
         }
}//end selection sort
 
3.    Bubble Sort
 
Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order
#include <iostream>
using namespace std;
int compare(int, int);
void sort(int[], const int);
int compare(int x, int y)
{
     return(x > y);
}
void sort(int table[], const int n)
{
int t;
     for(int i = 0; i < n; i++)
     {
          for(int j = 0; j < n-1; j++)
          {
               if(compare(table[j], table[j+1]))
{
t=table[j];
table[j]=table[j+1];
table[j+1]=t;
 
}                    
          }
     }
}
int quantity;
int tab[100];
 
int main()
{
cout << "Input quantity: ";
cin >> quantity;
cout << "Input numbers: \n\n";
for (int i = 0; i < quantity; i++)
{
    int x = i;
    cout << "#" << ++x << ": ";
    cin >> tab[i];
}
cout << "\nBefore sorting: ";
for (int i = 0; i < quantity; i++)
{
     cout << tab[i] << " ";
}
 
cout << "\nAfter sorting: ";
sort(tab, quantity);
for(int i = 0; i < quantity; i++)
{
     cout << tab[i] << " ";
}
return 0;}
 
Two-Dimensional Arrays
A 2-dimensional array is an array of arrays. In other words, it is an array where each member of the array is also an array. Consider the below table
 

Country\Data
Map
Flag
Area (sq km)
Population
United States
9,629,091
272,639,608
Cameroon
475,440
15,456,092
Guatemala
108,890
12,335,580
Italy
301,230
56,735,130
Oman
212,460
2,446,645

Declaring and Initializing a 2-Dimensional Array

Like the above table, a 2-dimensional array is made rows and columns. To declare it, use double pair of a opening and closing square brackets. Here is an example:

int numberOfStudentsPerClass[12][50];

Based on this, when initializing a 2-dimensional array, make sure you provide a number of values that is less than or equal to the number of members.

Here is an example:

double distance[2][4] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12};
 
Processing a 2-Dimensional Array
 
#include <iostream>
int main()
{
               double distance[][4] = {
                                                             { 44.14, 720.52,  96.08,  468.78 },
                                                             {  6.28,  68.04, 364.55, 6234.12 }
                                                   };
 
               // Scan the array from the 3rd to the 7th member
               cout << "Members of the array";
               for(int i = 0; i < 2; ++i)
                               for(int j = 0; j < 4; ++j)
                                              cout << "\nDistance [" << i << "][" << j << "]: " << distance[i][j];
 
               cout << endl;
               return 0;
}
 

STACKS

 

Stacks are commonly used Data Structures while writing code. It's concept is really simple which makes it even simpler to write it in code. Consider this  situation. There are a pile of 5 Books on a Table. You want to add one book to the pile. What do you do? You simply add the book on the TOP of the pile. What if you want the third book from the new 6 book pile? You then lift each book one by one from the TOP until the third book reaches the top. Then you take the third book and replace all the others back into the pile by adding them from the TOP.

 

#include <iostream>

#define MAX 10        // MAXIMUM STACK CONTENT

class stack

{

  private:

    int arr[MAX];   // Contains all the Data

    int top;        //Contains location of Topmost Data pushed onto Stack

  public:

             stack()         //Constructor

             {

                top=-1;      //Sets the Top Location to -1 indicating an empty stack

             }

             void push(int a)  // Push ie. Add Value Function

             {

                        top++;        // increment to by 1

                        if(top<MAX)

                         {

                                    arr[top]=a;  //If Stack is Vacant store Value in Array

                         }

                         else

                         {

                                    cout<<"STACK FULL!!"<<endl;

                                    top--;

                         }

             }

            int pop()                  // Delete Item. Returns the deleted item

            {           if(top==-1)

                        {

                                    cout<<"STACK IS EMPTY!!!"<<endl;

                                    return NULL;

                        }

                        else

                        {           int data=arr[top];     //Set Topmost Value in data

                                    arr[top]=NULL;       //Set Original Location to NULL

                                    top--;               // Decrement top by 1

                                    return data;         // Return deleted item

                        }

             }

};

 

int main()

{

 stack a;

 a.push(3);

 cout<<"3 is Pushed\n";

 a.push(10);

 cout<<"10 is Pushed\n";

 a.push(1);

 cout<<"1 is Pushed\n\n";

 cout<<a.pop()<<" is Popped\n";

 cout<<a.pop()<<" is Popped\n";

 cout<<a.pop()<<" is Popped\n";

 return 0;

}

 

Output:

3 is Pushed

10 is Pushed

1 is Pushed

 

1 is Popped

10 is Popped

3 is Popped

 

Clearly we can see that the last data pushed is the first one to be popped out.That's why a Stack is also known as a LIFO Data Structure which stands for "LastIn,First Out" and I guess you know why.

 

Let us see how we implemented the stack. We first created a variable called top that points to the top of the stack. It is initialised to -1 to indicate that the stack is empty. As Data is entered, the value in top increments itself and data is stored into an array arr. Now there's one drawback to this Data Structure. Here we state the Maximum number of elements as 10. What if we need more than 10 Data Elements? In that case we combine a Stack along with a Linked List which will be explained later.

1. Array implementation


The array implementation aims to create an array where the first element (usually at the zero-offset) is the bottom. That is, array[0] is the first element pushed onto the stack and the last element popped off. The program must keep track of the size, or the length of the stack. The stack itself can therefore be effectively implemented as a two-element structure in C:

    typedef struct {
        int size;
        int items[STACKSIZE];
    } STACK;

The push() operation is used both to initialize the stack, and to store values to it. It is responsible for inserting (copying) the value into the ps->items[] array and for incrementing the element counter (ps->size). In a responsible C implementation, it is also necessary to check whether the array is already full to prevent an overrun.

    void push(STACK *ps, int x)
    {
        if (ps->size == STACKSIZE) {
            cout<<"Error: stack overflow\n";
            abort();
        } else 
            ps->items[ps->size++] = x;
    }

The pop() operation is responsible for removing a value from the stack, and decrementing the value of ps->size. A responsible C implementation will also need to check that the array is not already empty.

    int pop(STACK *ps)
    {
        if (ps->size == 0){
            cout<<"Error: stack underflow\n";
            abort();
        } else 
            return ps->items[--ps->size];
    }

 

2. Linked list implementation


The linked-list implementation is equally simple and straightforward. In fact, a stack linked-list is much simpler than most linked-list implementations: it requires that we implement a linked-list where only the head node or element can be removed, or popped, and a node can only be inserted by becoming the new head node.

Unlike the array implementation, our structure typedef corresponds not to the entire stack structure, but to a single node:

    typedef struct stack {
        int data;
        struct stack *next;
    } STACK;

Such a node is identical to a typical linked-list node, at least to those that are implemented in C.

The push() operation both initializes an empty stack, and adds a new node to a non-empty one. It works by receiving a data value to push onto the stack, along with a target stack, creating a new node by allocating memory for it, and then inserting it into a linked list as the new head:

    void push(STACK **head, int value)
    {
        STACK *node =new STACK;  /* create a new node */
 
        if (node == NULL){
            cout<<"Error: no space available for node\n";
            abort();
        } else {                                      /* initialize node */
            node->data = value;
            node->next = empty(*head) ? NULL : *head; /* insert new head if any */
            *head = node;
        }
    }

A pop() operation removes the head from the linked list, and assigns the pointer to the head to the previous second node. It check whether the list is empty before popping from it:

    int pop(STACK **head)
    {
        if (empty(*head)) {                          /* stack is empty */
           cout<<"Error: stack underflow\n";
           abort();
        } else {                                     /* pop a node */
            STACK *top = *head;
            int value = top->data;
            *head = top->next;
            Delete top;
            return value;
        }
    }

Infix, Postfix and Prefix

 

Infix notation: X + Y

Operators are written in-between their operands. This is the usual way we write expressions. An expression such as A * ( B + C ) / D is usually taken to mean something like: "First add B and C together, then multiply the result by A, then divide by D to give the final answer." Infix notation needs extra information to make the order of evaluation of the operators clear: rules built into the language about operator precedence and associativity, and brackets ( ) to allow users to override these rules.

Postfix notation (also known as "Reverse Polish notation"): X Y +

 

Operators are written after their operands. The infix expression given above is equivalent to A B C + * D /. The order of evaluation of operators is always left-to-right, and brackets cannot be used to change this order. Because the "+" is to the left of the "*" in the example above, the addition must be performed before the multiplication. Operators act on values immediately to the left of them.

 

Prefix notation (also known as "Polish notation"): + X Y

 

Operators are written before their operands. The expressions given above are equivalent to / * A + B C D. As for Postfix, operators are evaluated left-to-right and brackets are superfluous. Operators act on the two nearest values on the right. I have again added (totally unnecessary) brackets to make this clear:

(/ (* A (+ B C) ) D)

Examples:

 

Infix
Postfix
Prefix
Notes
A * B + C / D
A B * C D / +
+ * A B / C D
multiply A and B, divide C by D, add the results
A * (B + C) / D
A B C + * D /
/ * A + B C D
add B and C, multiply by A, divide by D
A * (B + C / D)
A B C D / + *
* A + B / C D
divide C by D, add B, multiply by A

 


 

                        Example-1


QUEUES

 

There's a huge crowd at your local grocery store. There are too many people trying to buy their respective items and the Shopkeeper doesnt know from where to start. Everyone wants their job done quickly and the shopkeeper needs an efficient method to solve this problem. What does he do? He introduces a Queue System based on the First Come, First Serve System. The Last Person trying to

buy an item stands behind the last person at the END of the queue. The Shopkeeper however is present at the FRONT end of the queue. He gives the item to the person in FRONT of the queue and after the transaction is done, the person in FRONT of the Queue Leaves. Then the person second in queue becomes the First person in the Queue.


 



 

 


 

 

 

/*          QUEUE IMPLEMENTATION                        */

#include <iostream>

#define MAX 5           // MAXIMUM CONTENTS IN QUEUE

 

class queue

{

 private:

            int t[MAX];

            int al;      // Addition End

            int dl;      // Deletion End

 

 public:

  queue()

  {

            dl=-1;

            al=-1;

  }

  void del()

  {

     int tmp;

     if(dl==-1)

     {

                cout<<"Queue is Empty";

     }

     else

     {

                        for(int j=0;j<=al;j++)

                        {

                                    if((j+1)<=al)

                                    {

                                                tmp=t[j+1];

                                                t[j]=tmp;

                                    }

                                    else

                                    {

                                                al--;

 

                                    if(al==-1)

                                                dl=-1;

                                    else

                                                dl=0;

                                    }

                        }

     }

  }

void add(int item)

{

            if(dl==-1 && al==-1)

            {

                        dl++;

                        al++;

            }

   else

   {

                        al++;

                        if(al==MAX)

            {

                                    cout<<"Queue is Full\n";

                                    al--;

                                    return;

                        }

            }

            t[al]=item;

 

}

  void display()

  {

            if(dl!=-1)

   {

            for(int i=0;i<=al;i++)

            cout<<t[i]<<" ";

   }

   else

            cout<<"EMPTY";

  }

 

};

 

int main()

{

 queue a;

 int data[5]={32,23,45,99,24};

 

 cout<<"Queue before adding Elements: ";

 a.display();

 cout<<endl<<endl;

 

 for(int i=0;i<5;i++)

 {

   a.add(data[i]);

   cout<<"Addition Number : "<<(i+1)<<" : ";

   a.display();

   cout<<endl;

 }

 cout<<endl;

 cout<<"Queue after adding Elements: ";

 a.display();

 cout<<endl<<endl;

 

 for(i=0;i<5;i++)

 {

   a.del();

   cout<<"Deletion Number : "<<(i+1)<<" : ";

   a.display();

   cout<<endl;

 }

 return 0;

}

OUTPUT:

Queue before adding Elements: EMPTY

 

Addition Number : 1 : 32

Addition Number : 2 : 32 23

Addition Number : 3 : 32 23 45

Addition Number : 4 : 32 23 45 99

Addition Number : 5 : 32 23 45 99 24

 

Queue after adding Elements: 32 23 45 99 24

 

Deletion Number : 1 : 23 45 99 24

Deletion Number : 2 : 45 99 24

Deletion Number : 3 : 99 24

Deletion Number : 4 : 24

Deletion Number : 5 : EMPTY

 

As you can clearly see through the output of this program that addition is

always done at the end of the queue while deletion is done from the front end of

the queue

 

QUEUES WITH LINKED LIST IMPLEMENTATION

 

Similar to the one above, the queued linked list removes the maximum data limit

as well. Here is the code:

 

#include <iostream>

struct node

{

   int data;

   node *link;

};

 

class lqueue

{

 private:

    node *front,*rear;

 public:

    lqueue()

    {

            front=NULL;

            rear=NULL;

    }

   

    void add(int n)

    {

            node *tmp;

            tmp=new node;

            if(tmp==NULL)

               cout<<"\nQUEUE FULL";

               

            tmp->data=n;

            tmp->link=NULL;

            if(front==NULL)

            {

                        rear=front=tmp;

                        return;

            }

            rear->link=tmp;

            rear=rear->link;

    }

    int del()

    {

            if(front==NULL)

            {

                        cout<<"\nQUEUE EMPTY";

                        return NULL;

            }

        node *tmp;

        int n;

        n=front->data;

        tmp=front;

        front=front->link;

        delete tmp;

        return n;

    }

   

    ~lqueue()

    {

            if(front==NULL)

               return;

            node *tmp;

            while(front!=NULL)

            {

                        tmp=front;

                        front=front->link;

                        delete tmp;

            }

     }

};

 

int main()

{

            lqueue q;

            q.add(11);

            q.add(22);

            q.add(33);

            q.add(44);

            q.add(55);

            cout<<"\nItem Deleted = "<<q.del();

            cout<<"\nItem Deleted = "<<q.del();

            cout<<"\nItem Deleted = "<<q.del();

            return 0;

}

 

CIRCULAR QUEUES WITH ARRAY IMPLEMENTATION

 

#include<iostream.h>

#include<stdlib.h>

#include<stdio.h>

#include<conio.h>

 

// Defining class CQUEUE

class cqueue

 {

   int q[10],num,front,rear;

   public :

            cqueue();

            void insert();

            void remove();

            void menu();

            void display();

 };

 

cqueue :: cqueue()

 {

   front=rear=0;

 }

 

void cqueue :: insert()

 {

   if(((rear+1)%10)==front)

    {

      cout<<"Queue is full";

    }

   else

    {

      cout<<"Please enter a number : ";

      cin>>

      q[rear];

      rear=(rear+1)%10;

    }

 }

 

void cqueue :: remove()

 {

   if(rear==front)

    {

      cout<<"Queue is empty";

    }

   else

    {

      int num=q[front];

      cout<<"You deleted "<<num<<"";

      front=(front+1)%10;

      getch();

    }

 

 }

void cqueue::display()

 {

   int i=front;

   if(front==rear)

    {

      cout<<"Queue is empty, No elements to display !!!!!!  ";

    }

   else

    {

      cout<<"Queue's elements are :";

      cout<<"Front = ";

      while( i!=rear)

       {

            if(i==(rear-1)) cout<<"Rear = ";

            cout<<q[i]<<"";

            i=i++%10;

 

       } // end while.

    }// end elseif.

   getch();

 }

 

void cqueue :: menu()

 {

   int ch=1;

   clrscr();

   while (ch)

    {

      clrscr();

      cout<<"Enter your Choice

1 : insert

2 : remove

3 : display

0 :

exit";

 

      cin >>ch;

      switch (ch)

       {

             case 1 : insert();

                          break;

             case 2 : remove();

                          break;

             case 3 : display();

                          break;

             case 0 : exit(0);

       }

    }

 }

void main()

 {

  cout<<"Program to demonstrate Circular Queue";

  cqueue q1;

  q1.menu();

 }

Popular posts from this blog

XII- CS-- SOLVED SQL queries (SQL PRACTICAL ASSIGNMENS)

SQL--HOME ASSIGNMENTS(XII Class)

Python-MySQL Connectivity