By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,469 Members | 1,885 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,469 IT Pros & Developers. It's quick & easy.

priority queue by stack(( have code that I am strugling to write ))

P: 3
I have code that I am strugling to write could u plz help me with it ...I 'll be thankfull
Implement a Priority Queue using Stacks. I am not allowed to use any other data structure. Example:

Class PriorityQueue

{
Stack PQ;


.
}
I should implement the following interface:

Public void insert (double data, int priority) {}
Public double remove () { }
Public boolean is-empty() { }
Public double peekmin() {}
Public int size () {}
Public remove (int n) { } // remove the element number n
Nov 26 '06 #1
Share this Question
Share on Google+
2 Replies


Ganon11
Expert 2.5K+
P: 3,652
Implementing a Queue using stacks!? That's just craziness. A Stack is a LIFO structure - last in first out, while a Queue is a FIFO structure - first in first out. They're completely different.

I guess the biggest thing to do is insert. In order to do that, you'd take the following steps:

1) Declare an array of stack nodes with size equal to the stack's size.
2) From 0 to size - 1, pop each node of the stack and set the nodeArray at the position to the node. For example:

Expand|Select|Wrap|Line Numbers
  1. nodeArray[0] = PQ.pop();
  2. nodeArray[1] = PQ.pop();
Of course, you'd use a for... loop for this.

3) The stack is now empty. Add the node given to the function as a parameter to the stack.
4) Finally, traverse your node array backwards, inserting each node onto the stack again.

That would be a generic queue insert function - doing it this way means that the function to get the first node in the queue would be the same as the stack.pop() function.

Of course, I'm not all too familiar with priority queues - you may have to insert the extra node somewhere in the array based on its priority. That would have to happen between steps 2 and 3.

Good luck!
Nov 26 '06 #2

P: 3
THank u for helpin me I know it is totally diffrient but my doctor wrote it ^_^
Nov 28 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.