栈
1.栈是一种线性表,但限定这种线性表只能在某一端进行插入或删除的操作,栈的特性:后进先出。
栈顶:允许进行插入和删除的那一端
栈厎:固定的,不允许进行插入或删除的另一端。
n个不同元素进栈,出栈元素不同排列的个数为1/(n+1)C2nn
1.顺序栈
typedef int ElemType;
#define true 1
#define false 0
#define MaxSize 100//定义栈中元素的最大个数
typedef struct {
ElemType data[MaxSize];//存放栈中元素的一维数组
int top;//栈顶指针
}SqStack;
//栈顶指针S.top,初始时设-1,栈顶元素S.data[S.top]
// 栈空:S.top==-1,栈满:S.top==MaxSize-1,栈长:S.top+1;
//初始化
void InitStack(SqStack* S) {
S->top = -1;
}
//判栈空
int IsEmptyStack(SqStack S) {
if (S.top == -1)
return true;
else
return false;
}
//进栈
int Push(SqStack* S, ElemType x) {
if (S->top == MaxSize - 1)
return false;
S->top++;
S->data[S->top] = x;
return true;
}
//出栈
int Pop(SqStack* S, ElemType* x) {
if (S->top == -1)
return false;
*x = S->data[S->top];
S->top--;
return true;
}
//读取栈顶元素
int GetTop(SqStack *S, ElemType *x) {
if (S->top == -1)
return false;
*x = S->data[S->top];
}
2.多栈共享技术:最常用的是两个栈的共享技术,双端栈,两个栈共享一片空间,提高内存资源利用率.
#include "stdlib.h"
#include "stdio.h";
#include "stdbool.h"
#define M 100
#define StackElemType int
typedef struct {
StackElemType Stack[M];
StackElemType top[2];
}DqStack;
void InitStack(DqStack* S) {
S->top[0] = -1;
S->top[1] = M;
}
int Push(DqStack* S, StackElemType x, int i) {
if (S->top[0] + 1 == S->top[1])
return false;
switch (i){
case 0:
S->top[0]++;
S->Stack[S->top[0]] = x;
break;
case 1:
S->top[1]--;
S->Stack[S->top[1]] = x;
break;
default:
return false;
}
return true;
}
int Pop(DqStack* S, StackElemType* x, int i) {
switch (i) {
case 0:
if (S->top[0] == -1)
return false;
*x = S->Stack[S->top[0]];
S->top[0]--;
break;
case 1:
if (S->top[1] == M)
return false;
*x = S->Stack[S->top[1]];
S->top[1]++;
break;
default:
return false;
}
return true;
}
3.链栈
链栈即采用链表作为存储结构实现的栈,链表的表头指针就作为栈顶指针,栈顶指针始终指向当前栈顶元素前面的头结点。若top->next==NULL,则代表栈空。
采用链栈不必预先估计栈的最大容量,只要系统有可用空间,链栈就不会出现溢出,对于链栈,在使用完毕时,应该释放相应空间。
#include "stdlib.h"
#include "stdio.h"
#define true 1
#define false 0
typedef int ElemType;
typedef struct node {
ElemType data;
struct node* next;
}LinkStackNode;
typedef LinkStackNode* LinkStack;
//链栈进栈
int Push(LinkStack top, ElemType x) {
LinkStackNode *temp;
temp = (LinkStackNode*)malloc(sizeof(LinkStackNode));
if (temp == NULL)//申请空间失败
return false;
temp->data = x;
temp->next = top->next;
top->next = temp;//修改当前栈顶指针
return true;
}
//链栈出栈
int Pop(LinkStack top, ElemType *x) {
LinkStackNode *temp;
temp = top->next;
if (temp == NULL)//栈空
return false;
top->next = temp->next;
*x = temp->data;
free(temp);
return true;
}