头文件及栈的结构体:
#include<iostream>
#include<stdio.h>
using namespace std;
const int STACK_INIT_SIZE = 100;
const int STACKINCREASE = 10;
typedef struct
{
int* base; //栈底指针
int* top; //栈顶指针
int stacksize; //栈长度
}SqStack;
创建栈的crease函数:
SqStack* crease() //创建栈并初始化
{
SqStack* L;
L = (SqStack*)malloc(sizeof(SqStack));
L->base = (int*)malloc(sizeof(int) * STACK_INIT_SIZE); //base指向分配的内存的头
L -> top = L->base;
L->stacksize = STACK_INIT_SIZE; //创建一个名为L的栈并初始化
return L;
}
往栈里面添加数据的insert函数:
void insert(SqStack* L,int n) //进栈(向栈中插入n个元素)
{
int x;
cin >> x;
*(L->top) = x;
for (int k = 0; k < n-1; k++)
{
cin>>x;
L->top = (L->top) + 1;
*(L->top) = x;
L->stacksize += 1;
}
}
查看栈的长度Longstack函数:
int Longstack(SqStack* L) //栈长
{
return (int)(L->top - L->base)+1; //两指针相减等于两指针之间指针指向类型的数量
}
出栈的out函数:
void out(SqStack* L, int n) //出栈(从栈中去除n个元素)
{
L->top -= n;
}
打印栈的所有数据Pirnt函数:
void Print(SqStack *L) //打印栈中字符
{
int* Run = L->top; //定义一个run指针用于从栈顶向栈底遍历整个栈
while ((Run) != (L->base)) //遍历指针不等于栈底的时候打印字符
{
cout << *(Run) << ',';
Run -= 1;
}
cout << *(Run) << endl; //在上面的判断条件下实际上栈底的那个字符不会被打印
}
销毁栈的Destroy函数:
void Destroy(SqStack* L) { //销毁栈
free(L->base); //释放栈存储空间
L->base = L->top = NULL; //栈顶指针栈底指针指向空
L->stacksize = 0; //栈长度归零
}
主函数main():有测试数据
int main()
{
int count = 0;
int n = 10;
SqStack* L;
L = crease();
insert(L, n);
Print(L);
count = Longstack(L);
cout << count << endl;
out(L, 4);
Print(L);
Destroy(L); //使用完后记得清空栈
}