# Thread: How to change my stack into a queue?

1. ## How to change my stack into a queue?

Without using templates, how can I convert my stack class into a queue class? I can't find anything on the web.

Code:
```class Stack
{
private:
int stack[100];
int top;
public:
Stack(): top(0) { }
~Stack() {}

void push(int x)
{
if (top < 100)
stack[top++] = x;
}

int pop()
{
if (top > 0)
return stack[--top];
else
return 0;
}

void clear() { top = 0; }
int isEmpty() { return top == -1; }
int isFull() { return top == 100; }
};```

2. The different between a stack and a queue is this:
Stack: First in, Last out (FILO)
Queue: First in, First out (FIFO)

Now when using a fix size array its actually pretty easy. You just need to keep track of the apparent head and apparent tail and just make the array circular.

3. I'm sure my logic is messed up, but is this a good start?

Code:
```class Queue
{
private:
int stack[100];
int bottom;
public:
Queue(): bottom(100) {}
~Queue() {}

void push(int x)
{
if (bottom > 0)
stack[bottom--] = x;
}

int pop()
{
if (bottom > 0)
{
return stack[bottom + 1];
}
}
};```
I input 1 2 3, and I get this output..
1122450
1122450
1122450

4. In your pop you should change to top of the stack (or bottom, or whatever you call it). Otherwise you'll keep popping the same value.

5. No luck..

6. heres how I could define the private variables:
Code:
```class Queue
{
private:
int stack[100];
int* top;
int* bottom;```
You then keep track of the top and bottom, you pop from the top and push to the bottom. As you pop and push the pointers get incremented and once they reach the end of the array they go back to teh beginning.

7. Ok now I'm just confused. Thanks for the efforts. I guess I learn by seeing a full code example, and I practice rewriting it so I understand how it works. Visual learner? I don't know.

8. Code:
```class Queue {
private:
int queue[100];
int top;
int bottom;

public:
Queue() : top(0), bottom(0) {}

void push(int x) {
queue[top] = x;

if(top >= 99) top = 0;
else top ++;
}

int pop(void) {
int x = queue[bottom];

if(bottom <= 99) bottom = 0;
else bottom ++;

return x;
}
};```
Something like that.

9. Thanks for the help.

Popular pages Recent additions