1.栈的概述
栈的主要特点是后进先出(last in first out,LIFO),即出栈元素只能是位于栈顶的元素,入栈也只能在栈顶。
栈是只能在一端(栈顶)进行插入或删除的线性表。
n个元素依次入栈,可在任意时刻出栈,则共有
种可能。
栈的存储结构:
2.顺序栈代码实现
#ifndef _SEQSTACK_H
#define _SEQSTACK_H
#include<iostream>
using namespace std;
template<class T>
class SeqStack
{
public:
SeqStack(int msize=10):top(-1),size(msize)
{
ptr=new T[size];
if (ptr==NULL)
{
cout<<"创建失败!"<<endl;
exit(1);
}
}
~SeqStack()
{
delete [] ptr;
}
void push(const T item);
T pop();
void print() const;
T getTop() const;
bool isFull() const
{
return top==size-1;
}
bool isEmpty() const
{
return top==-1;
}
void makeEmpty()
{
top=-1;
}
private:
int top;
T *ptr;
int size;
};
template<class T>
void SeqStack<T>::push(const T item)
{
if(isFull())
{
cout<<"The stack is full!"<<endl;
exit(1);
}
ptr[++top]=item;
}
template<class T>
T SeqStack<T>::pop()
{
if(isEmpty())
{
cout<<"The stack is empty!"<<endl;
exit(1);
}
return ptr[top--];
}
template<class T>
T SeqStack<T>::getTop() const
{
if(isEmpty())
{
cout<<"The stack is empty!"<<endl;
exit(1);
}
return ptr[top];
}
template<class T>
void SeqStack<T>::print() const
{
if(isEmpty())
{
cout<<"The stack is empty!"<<endl;
exit(1);
}
cout<<"Bottom--->";
for(int i=0;i<=top;i++)
{
cout<<ptr[i]<<"--->";
}
cout<<"Top"<<endl<<endl<<endl;
}
#endif
3.链栈的代码实现
#ifndef _LISSTACK_H
#define _LISSTACK_H
#include<iostream>
using namespace std;
template<class T>
class LinkStack
{
public:
LinkStack():top(NULL){}
~LinkStack()
{
MakeEmpty();
}
void push(const T item);
T pop();
T GetTop() const;
void Print() const;
void MakeEmpty();
bool IsEmpty() const
{
return top==NULL;
}
private:
struct StackNode
{
T data;
StackNode *next;
StackNode(const T mdata,StackNode *n=NULL):data(mdata),next(n){}
};
StackNode *top;
};
template<class T>
void LinkStack<T>::push(const T item)
{
top=new StackNode(item,top);
}
template<class T>
T LinkStack<T>::pop()
{
if(IsEmpty())
{
cout<<"The stack is empty!"<<endl;
exit(1);
}
StackNode *tem=top;
top=top->next;
T mdata=tem->data;
delete tem;
return mdata;
}
template<class T>
T LinkStack<T>::GetTop() const
{
if(IsEmpty())
{
cout<<"The stack is empty!"<<endl;
exit(1);
}
return top->data;
}
template<class T>
void LinkStack<T>::Print() const
{
StackNode *tem=top;
cout<<"Top--->";
while(tem!=NULL)
{
cout<<tem->data<<"--->";
tem=tem->next;
}
cout<<"Bottom"<<endl<<endl;
}
template<class T>
void LinkStack<T>::MakeEmpty()
{
StackNode *tem;
while(top!=NULL)
{
tem=top;
top=top->next;
delete tem;
}
}
#endif
3.栈的应用
3.1括号匹配检测
3.2递归算法改为非递归算法需要用到栈,但不是所有的转变算法都用到栈,如斐波那契数列的非递归算法只需要循环。
3.3函数调用时,系统要用栈保存必要的信息