请教:用C语言写栈
我想用C语言实现栈,我的思路是用单链表的逆置来实现栈的“先进后出”,但感觉麻烦;有没有别的简单一点的方法,请教各位!
#include<iostream> #include<exception> using namespace std; template<class Type> struct node { Type key; node *next; node(Type k):next(NULL){ key=k;} node<Type>(node<Type> & n){ this->key=n->key; this->next=n->next; } ~node(){ next=NULL;} }; template<class Type> class stack { private: size_t Size; node<Type> *tail; node<Type> *top; public: stack<Type>():top(NULL),tail(NULL),Size(0){} void push(Type n){ node<Type> *point=new node<Type>(n); try { point->next=top; top=point; }catch ( exception e) { } } Type pop() { node<Type> *tmp; Type k; try{ if( tail == top ) { throw exception(); } tmp=top; top=top->next; k=tmp->key; delete tmp; return k; }catch ( exception e ) { cout<<e.what(); exit (1); } } size_t size(){return Size;} }; int main() { stack<int> st; st.push(1); st.push(2); st.push(3); cout<<st.pop()<<endl; cout<<st.pop()<<endl; cout<<st.pop()<<endl; return 0; }