Data structures and algorithms Assignment Queues

Here is the Data Structures and Algorithms Assignment No 02 of Queues

Question:

Write the definition of the function moveNthFront( ) that takes as a parameter a positive integer, n. The function moves the nth element of the queue to the front. The order of the remaining elements remains unchanged. For example, suppose

queue = {5, 11, 34, 67, 43, 55} and n = 3.

After a call to the function moveNthFront( ),

queue = {34, 5, 11, 67, 43, 55}

Add this function to the class that you have defined for the queue. Also, write a program to test your method. The queue has to be implemented using a linked list.

Code:

Here is the complete code for the Data Structures and Algorithms Assignment of Queues

#include<iostream>

using namespace std;

class Node
{
public:
int data;
Node* next;
};

class Queue
{
public:
Node* front;
Node* last;

Queue()
{
    front=NULL;
    last=NULL;  
}   

void Insert_Node(int x)
{
    Node *newnode = new Node;
    newnode->data = x;

    if (front==NULL)
    {
        front = new Node;
        front->data = x;
        front->next = NULL;
        last = front;   
    }
    else
    {
        Node *newnode = new Node;
        newnode->data = x;
        last->next = newnode;
        newnode->next = NULL;
        last = newnode; 
    }   
}

void display_node()
{
    Node* temp = front;
    while (temp!=NULL)
    {
        cout<<temp->data<<"  ";
        temp = temp->next;  
    }   
}

void move_nth_to_front(int change)
{
    Node* temp = front;
    Node* temp1 = front;
    if (change>2)
    {

    for (int i=1;i<change;i++)
    {
        front = front->next;
        if (i!=change-2)
        temp1 = temp1->next;    
    }           

    temp1->next = front->next;
    front->next = temp; 
    }

    else if (change==1)
    cout<<"THE NUMBER 1 IS ALREADY AT THE FRONT";

    else if (change ==2)
    {
        for (int i=1;i<change;i++)
    {
        front = front->next;    
    }
    temp1->next = front->next;
    front->next = temp;

    }


}    

};

int main()
{
Queue* q = new Queue;
int check,size=0;
int to_front;
do{
cout<<"ENTER A VALUE TO ADD INTO THE QUEUE OR -1 TO EXIT: "; cin>>check;
if (check!=-1)
{
q->Insert_Node(check);
size++;
}

    else 
    break;
}while (check!=-1);
cout<<"\n\n--------QUEUE DISPLAYING BEFORE CHANGING----------\n\n";
q->display_node();

cout<<"\n\nENTER THE NO OF NODE THAT YOU WANT TO BRING TO FRONT: ";
cin>>to_front;

while(to_front>size)
{
    cout<<"ENTER THE CORRECT NODE YOU WANT TO BRING TO FRONT: ";
    cin>>to_front;
}

q->move_nth_to_front(to_front);
cout<<endl;
cout<<"\n\n--------QUEUE DISPLAYING BEFORE CHANGING----------\n\n";
q->display_node();

}

For more details about Data Structures and Algorithms Assignment of Huffman coding click here

For other assignments and quizzes click here 

Output:

Data structures and algorithms Assignment Queues

Leave a Reply

Your email address will not be published. Required fields are marked *