pop()函数有什么问题,为什么它不能正常工作?
class stack{
int *p, *Cursor;
int size ;
public:
stack(int sz) {Cursor = p = new int[size=sz+1];} //consider the stack empty when its size is 1
~stack() {delete[] p;} //Cursor and P will be destroyed when the program finishes
void push(int x) {Cursor+=1; *Cursor=x; size++;}
int pop() {if(Cursor == p) return -1; int temp = *Cursor; Cursor--; size--; return (temp);}
bool isEmpty(){return(Cursor == p);}
bool isFull(){return(Cursor == p+size);}
};
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
stack A(3);
std::cout<<"Empty: "<<A.isEmpty()<<std::endl;
std::cout<<"Full: "<<A.isFull()<<std::endl;
A.push(10);
A.push(20);
A.push(30);
std::cout<<std::endl;
std::cout<<" 1st pop: "<<A.pop()<<std::endl<<" 2nd pop: " <<A.pop()<<std::endl<<" 3rd pop: " <<A.pop()<<std::endl<<" 4th pop: " <<A.pop()<<std::endl;
Run Code Online (Sandbox Code Playgroud)
我得到的输出是:
1st pop: -1
2nd pop: 10
3rd pop: 20
4th pop: 30
Run Code Online (Sandbox Code Playgroud)
虽然我应该得到......
1st pop: 30
2nd pop: 20
3rd pop: 10
4th pop: -1
Run Code Online (Sandbox Code Playgroud)
问题是我哪里出错了?