栈是一种先进后出的数据结构,栈的使用有递归和四则运算表达式求值
栈的每一个节点都有一个指针域和值,进栈和出栈操作都是通过栈顶指针上移和下移实现的
template<class T>
struct Node
{
T data;
Node<T> *next;
};
栈的基本操作有
1 元素进栈
2 元素出栈
3 获取栈顶的元素
4 判断栈是否为空
5 遍历栈
template<class T>
class LinkStack
{
private:
Node<T> *top;
public:
LinkStack()
{
top = NULL;
};
~LinkStack();
void push(T m);
T Pop();
T GetTop();
bool StackEmpty();
void ClearStack();
void StackTranverse();
};
栈基本操作的实现
template<class T>
LinkStack<T>::~LinkStack()
{
Node<T> *q;
while(top)
{
q = top;
top = top->next;
delete q;
}
}
template<class T>
void LinkStack<T>::push(T m)
{
Node<T> *s;
s = new Node<T>;
s->data = m;
s->next = top;
top = s;
}
template<class T>
T LinkStack<T>::Pop()
{
if(top == NULL)
throw "溢出";
else
{
Node<T> *s;
s = top;
T m = s->data;
top = s->next;
delete s;
return m;
}
}
template<class T>
T LinkStack<T>::GetTop()
{
if(top == NULL)
throw "栈空";
return top->data;
}
template<class T>
bool LinkStack<T>::StackEmpty()
{
if(top == NULL)
return true;
else
return false;
}
template<class T>
void LinkStack<T>::ClearStack()
{
while(top)
{
Node<T> *q;
q=top;
top=top->next;
delete q;
}
}
template<class T>
void LinkStack<T>::StackTranverse()
{
Node<T> *p;
p = top;
while(p)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
int main()
{
LinkStack<int> *stack = new LinkStack<int>;
for(int i=0;i<=10;i++)
{
stack->push(i);
}
stack->StackTranverse();
cout<<"---------------------------------------"<<endl;
cout<<stack->Pop()<<endl;
cout<<"----------------------------------------"<<endl;
cout<<stack->GetTop()<<endl;
cout<<"----------------------------------------"<<endl;
stack->StackTranverse();
return 0;
}
对比顺序栈和链式栈,他们的时间复杂度是一样,都为O(1),如果栈在使用过程中,元素变化不可预料,有时大有时小,可以用链式栈,反之 如果变化可控,用顺序栈好点