实现一个简单的栈
#include<iostream>
using namespace std;
struct Node{
int data;
Node *next;
Node(int data, Node* next): data(data), next(next){}
};
class Stack{
private:
Node *head;
int count;
public:
Stack(): head(NULL), count(0){}
void Push(int to_push);
int Pop();
};
void Stack::Push(int to_push){
Node *new_node = new Node(to_push, head);
head = new_node;
++count;
}
int Stack::Pop(){
if(count == 0){
cerr<<"No Element to Pop"<<endl;
return -1;
}
Node *to_pop = head;
head = to_pop->next;
int ret = to_pop->data;
delete to_pop;
--count;
return ret;
}
int main()
{
Stack my_stack;
for(int i=0; i<10; ++i){
my_stack.Push(i);
}
for(int i=0; i<10; ++i){
cout<<my_stack.Pop()<<endl;
}
my_stack.Pop();
return 0;
}
注意思考,建立栈的形象思维:栈就是先进后出,弹出的总是最后一个进来的元素。
因此只需要记住每次改变后的head就可以,它是被弹出的。

浙公网安备 33010602011771号