棧的基本操作(c語言)
阿新 • • 發佈:2021-01-18
目錄
概念
- 棧是隻允許在一端進行插入或刪除操作的線性表
- 棧頂:只允許刪除或插入操作的一端。
- 棧頂:不允許許刪除或插入操作的一端。
- 特點:後進先出(LIFO:last in first out)
順序棧
#define MaxSize 10
儲存結構
typedef struct LNode{
int data[MaxSize];//
int top;//棧頂指標
}SqStack;
初始化
void InitStack(SqStack &s)
{
s.top=-1;//初始化棧頂指標
}
//進棧操作
進棧
bool PushStack(SqStack &s,int x)
{
if(s.top==MaxSize-1)return false;//棧滿
s.top++;
s.data[s.top]=x;
return true;
}
出棧
bool PopStack(SqStack &s,int &elem)
{
if(s.top==-1)return false;//棧空
elem=s.data[s.top];
s.top--;
return true;
}
讀取棧頂元素
bool GetTop(SqStack s,int &x)
{
if(s.top==-1)return false;//棧空
x=s.data[s.top];
return true;
}