如何才能C语言编程实现出栈与入栈?急!!!

如题所述

#ifndef LISTSTACK_H
#define LISTSTACK_H

#include <iostream.h>
#include <assert.h>
template <class Type> class Stack;
template <class Type>
class StackNode
{
friend class Stack<Type>;

private:
Type data;
StackNode<Type> *link;
StackNode(Type d=0,StackNode<Type> *l=NULL):data(d),link(l){}
};

template <class Type>
class Stack
{
public:
Stack():top(NULL){}
~Stack();
void Push(const Type &item);
Type Pop();
Type GetTop();
void MakeEmpty();
int IsEmpty() const { return top==NULL; }
private:
StackNode<Type> *top;
};

template <class Type>
Stack<Type>::~Stack()
{
MakeEmpty();
}

template <class Type>
void Stack<Type>::Push(const Type &item)
{
top=new StackNode<Type>(item,top);
}

template <class Type>
Type Stack<Type>::Pop()
{
assert(!IsEmpty());
StackNode<Type> *p=top;
Type revalue=p->data;
top=top->link;
delete p;
return revalue;
}

template <class Type>
Type Stack<Type>::GetTop()
{
assert(!IsEmpty());
return top->data;
}

template <class Type>
void Stack<Type>::MakeEmpty()
{
StackNode<Type> *p;
while(top!=NULL)
{
p=top;top=top->link;delete p;
}
}

#endif

#include "liststack.h"

int main()
{
Stack<int> stack;
for(int i=0;i<5;i++)
stack.Push(i*10+5);
for(i=0;i<4;i++)
{
cout<<stack.Pop()<<" ";
cout<<stack.GetTop()<<endl;
}

cout<<endl;

return 1;
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2008-01-22
我晕 拜托 别问这种问题好吧
回去自己看书去
相似回答