Here, I wrote a simple Queue Class Template:
#include "stdafx.h"
#include "iostream"
#include "conio.h"
template <class T> class Queue {
private:
struct Node {
T value;
Node *next;
};
Node *first, *last;
public:
Queue () { //Initialization
first = 0;
last = 0;
};
void push(T value) { //Put new value into Queue
Node *p = new Node;
p->value = value;
if (!first) //If Queue is not empty
first = p;
else
last->next = p;
last = p; //Put the value to the last of the Queue
};
T get() { //Get the first value of the Queue
return (first) ? first->value : NULL;
};
T pop() { //Take the first value out of Queue
T result = first->value;
Node *temp = first;
first = first->next;
delete temp;
return result;
};
};
int _tmain(int argc, _TCHAR* argv[])
{
Queue<int> bag;
bag.push(1); //Bag has value 1
bag.push(2); //Bag has values: 1, 2
std::cout << bag.get() << '\n' << bag.pop() << '\n' << bag.pop();
_getch();
return 0;
}
There is a problem - the output is:
0
2
1
/*
Correct output should be:
1
1
2
*/
When I debug the std::cout
line, I found out that program call bag.pop()
at the right most first, then the other bag.pop()
, at last the bag.get()
.
Is that the right order?