stack实现queue ; list实现stack

//栈实现队列

 

 #include<iostream> #include<stack> using namespace std; //implement queue use stack template<class T>class Queue { stack<T>st1,st2; public : void enqueue(T el) { st1.push(el); } T pop()//取栈顶,并弹出 { while(!st1.empty()) { st2.push(st1.top()); st1.pop(); } T w=st2.top(); st2.pop(); while(!st2.empty()) { st1.push(st2.top()); st2.pop(); } return w; } }; int main() { Queue<int> q; for(int i=1;i<=8;i++) { q.enqueue(i); } cout<<q.pop()<<endl; }

 

 

//链表实现栈

 

//implement stack by linked list #include<iostream> #include<list> using namespace std; template<class T>class Stack { list<T>li; public : void push(T el) { li.push_front(el); } T pop() { T ele=li.front(); li.pop_front(); return ele; } }; int main() { Stack<int>t; for(int i=1;i<=8;i++) { t.push(i); } cout<<t.pop()<<endl; }

你可能感兴趣的:(list)