Click here to Skip to main content
15,029,162 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, basically i am writing small stuff here and i am implementing queue using linked list and everything is at its peak but there is little thing that i cant understand which is that i am dequeueing and it is performing good but what if i want like i will also provide number of values to be deleted !! here is what i have done !!

What I have tried:

C++
#include<iostream>

#include<cstdlib>

using namespace std;

struct node{

    int info;

    struct node *next;

};

class Queue{

    private:

        node *rear;

        node *front;

    public:

        Queue();

        void enqueue();

        void dequeue();

        void display();

};

Queue::Queue(){

    rear = NULL;

    front = NULL;

}


void Queue::dequeue(){

    node *temp = new node;

    if(front == NULL){

        cout<<"\nQueue is Emtpty\n";

    }else{

        temp = front;

        front = front->next;

        cout<<"The data Dequeued is "<<temp->info;

        delete temp;

    }

}



int main(){

    Queue queue;


        queue.dequeue();


    return 0;

}
Posted
Updated 2-Jan-17 4:31am
Comments
Richard MacCutchan 2-Jan-17 10:54am
   
What happens if you want to remove an item that is not at the front of the queue?
mayashah 2-Jan-17 11:15am
   
is it possible ??
Richard MacCutchan 2-Jan-17 11:29am
   
Yes, of course it's possible. You just need to relink the two items either side of the one to be deleted.

1 solution

If you want to dequeue a specific number of values, you can use a loop:
C++
int count_to_dequeue = 3; // choose a number
while (count_to_dequeue > 0) {
    queue.dequeue();
    count_to_dequeue--;
}

How this works: first, you initialize a variable count_to_dequeue. In the example, it's 3, to dequeue three values. Then there is a while loop. It means "while count_to_dequeue is greater than zero, execute the code in the block". In the block, a value is dequeued and count_to_dequeue is decreased by one.

Full list of all steps that happen on runtime:

  1. count_to_dequeue is set to 3.
  2. (entering while loop)
  3. A value gets dequeued.
  4. count_to_dequeue gets decremented -> its value is 2.
  5. A value gets dequeued.
  6. count_to_dequeue gets decremented -> its value is 1.
  7. A value gets dequeued.
  8. count_to_dequeue gets decremented -> its value is 0.
  9. (while loop exists: count_to_dequeue is no longer greater than zero)
   
Comments
mayashah 2-Jan-17 10:35am
   
this could be done in main right ??
Thomas Daniels 2-Jan-17 10:37am
   
Yes, it can.
mayashah 2-Jan-17 10:41am
   
Amazing !! it worked !! Thank You
Thomas Daniels 2-Jan-17 10:46am
   
You're welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900