<分区>
在这里,我写了一个简单的队列类模板:
#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;
}
有一个问题 - 输出是:
0
2
1
/*
Correct output should be:
1
1
2
*/
当我调试 std::cout
行时,我发现程序首先调用最右边的 bag.pop()
,然后是另一个 bag.pop()
,最后是 bag.get()
。
这是正确的顺序吗?