Queue

This is a discussion on Queue within the C++ Programming forums, part of the General Programming Boards category; Any idea as to how to write a simple algorithm to reverse elements in a queue?...

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    10

    Question Queue

    Any idea as to how to write a simple algorithm to reverse elements in a queue?

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    If it's a double linked list, simply swap the Next and Previous pointers and swap the FirstNode and LastNode pointers.
    If not, you could create a new list (queue) by picking the first element in the old list, add it first to the new list, then remove it from the old list.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    I don't know if this helps, but the standard library provides such a facility...
    Code:
    #include <algorithm>
    #include <queue>
    
    std::queue<int> myqueue;
    for (int i = 0; i < 10; i++)
       myqueue.push(i);
    
    std::reverse(myqueue.begin(), myqueue.end());

  4. #4
    Registered User
    Join Date
    Feb 2003
    Posts
    595
    The essence of a queue is that elements are always added to the back of the line & elements are always removed from the front of the line. So if you just remove each element from the queue & add it to a new queue, you end up with a new queue exactly like the original one, in the same order.

    But, if you remove each element from the queue and push it onto a stack & continue doing this until the queue is empty & all of the elements are on the stack, and then pop each element off the stack & put it back on the queue, when you finish emptying the stack, your queue will end up with all of its elements in reverse order.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with FIFO QUEUE
    By jackfraust in forum C++ Programming
    Replies: 23
    Last Post: 04-03-2009, 08:17 AM
  2. Fixing my program
    By Mcwaffle in forum C Programming
    Replies: 5
    Last Post: 11-05-2008, 02:55 AM
  3. help with queues
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 05-21-2002, 09:09 PM
  4. help with queues
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 05-21-2002, 11:39 AM
  5. queue help
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 10-29-2001, 08:38 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21