栈的基本概念
栈的定义:栈是一种只能在一端进行插入或删除操作的线性表,
栈顶:允许进行插入或删除操作的一端称为栈顶
栈底:相对于栈顶在表的另一端,不能进行插入或删除操作的一端称为栈底,栈底是固定不变的。
入栈:向栈中插入元素
出栈:删除栈顶元素
栈最主要的特点就是先进后出(Last In First Out)
按照存储结构分,可以将栈划分为两种:顺序栈和链式栈
栈的结构体定义
//顺序栈的定义
typedef struct{
int data[maxSize]; //存放栈中的元素,maxSize为栈的大小
int top; //栈顶指针
}SqStack;
//链栈结点的定义
typedef struct LNode{
int data; //数据域
struct LNode *next; //指针域
}LNode;
顺序栈
两个状态:
- 栈空状态:
st.top == -1
或st.top == 0
,要根据不同的规定根据条件判定栈空状态,当为0时会浪费一个元素大小的空间 - 栈满状态:
st.top == maxSize - 1
。
两个操作:
- 元素进栈操作:
++(st.top);st.data[st.top] = x;
根据栈空状态的设定不同,可以有不同的操作方式,如先进栈后栈顶指针加1的操作方式。 - 元素出栈操作:
x=st.data[st.top];--(st.top);
进栈操作次序会决定出栈操作顺序。
顺序栈操作代码
//初始化栈
void initStack(SqStack &st){
st.top = -1;
}
//判断栈空
int isEmpty(SqStack st){
if(st.top == -1)
return 1;
return 0;
}
//入栈
int push(SqStack &st, int x){
if(st.top == maxSize - 1)
return 0;
++(st.top);
st.data[st.top] = x;
return 1;
}
//出栈
int pop(SqStack &st, int &x){
if(st.top == -1)
return 0;
x = st.data[st.top];
--(st.top);
return 1;
}
//注意:栈满不入栈,栈空不出栈,要记得判断。
链栈
两个状态:
- 栈空状态:
lst->next == NULL
- 栈满状态:可以说不存在栈满状态
两个操作:
- 元素进栈:
p->next = lst->next;lst->next = p
- 出栈操作:
p=lst->next; x=p->data;lst->next=p->next;free(p)
链栈基本操作代码
//初始化链栈
void initStack(LNode *&lst){
lst = (LNode *)malloc(sizeof(LNode));
lst->next = NULL;
}
//判断栈空
int isEmpty(LNode *lst){
if(lst->next == NULL)
return 1;
return 0;
}
//进栈
void push(LNode *lst, int x){
LNode *p;
p = (LNode *)malloc(sizeof(LNode));
p->next = NULL;
p->data = x;
p->next = lst->next;
lst->next = p;
}
//出栈
int pop(LNode *lst, int &x){
LNode *p;
if(lst->next == NULL)
return 0;
p = lst->next;
x = p->data;
lst->next = p->next;
free(p);
return 1;
}