栈分为链栈和顺序栈,分别和链表和顺序表挂钩
他们的结构分别的顺序表和单链表相似
#include<iostream>
#include<math.h>
#include<ctime>
#include<iomanip>
#include<stdlib.h>
#include<limits.h>//各种类型的范围库函数//常量库-2147483648 2147483647
#include<assert.h>
#include<malloc.h>
using namespace std;
#define STACK_MAX_INT 10
typedef int elemtype;
typedef enum state{ ok = 1,error=2 };
typedef struct seqstack
{
elemtype *data;
int maxsize;
int top;
}seqstcck;
state initstack(seqstack &s)
{
s.maxsize = STACK_MAX_INT;
s.data = (elemtype*)malloc(sizeof(elemtype)*s.maxsize);
memset(s.data, 0, sizeof(elemtype)*s.maxsize);
if (s.data == NULL) return error;
s.top = -1;
return ok;
}
void destroystack(seqstack &s)
{
free(s.data);
s.data = NULL;
s.maxsize = 0;
s.top = -1;
}
void clearstack(seqstack &s)//不改变栈的容量
{
s.top = -1;
}
int getsize(seqstack&s)
{
return s.top + 1;
}
bool emptystack(seqstack&s)
{
return getsize(s) == 0;
}
bool fullstack(seqstack&s)
{
return getsize(s) == s.maxsize;
}
bool inc_size(seqstack&s)
{
elemtype *newdata = (elemtype*)realloc(s.data, sizeof(elemtype)*s.maxsize*2);//要记得新建一个指针,如果内存不足realloc会失败从而导致数据丢失
if (NULL == newdata) //为了避免这种情况需要新指针,从而确保原来数据不会消失
{
return false;
}
s.data = newdata;
s.maxsize = s.maxsize * 2;
return true;
}
void pushstack(seqstack&s, elemtype val)//入栈的顺序时先抬栈在入数据,top是栈顶
{
if (!fullstack(s))
{
s.top += 1;
s.data[s.top] = val;//两条语句可以合并写作为s.data[++s.top]
}
else
{
if (inc_size(s))
pushstack(s, val);
else cout << "内存不足无法增容" << endl;
}
}
bool gettop(seqstack&s,elemtype&e)
{
if (!emptystack(s))
{
e= s.data[s.top];
return true;
}
else return false;
}
bool pop(seqstack&s, elemtype&e)
{
if (!emptystack(s))
{
e = s.data[s.top];
s.top -= 1;
return true;
}
else return false;
}
/*
void main()
{
seqstack mys;
initstack(mys);
pushstack(mys, 1);
pushstack(mys, 2);
pushstack(mys, 3);
cout << mys.data[mys.top - 2];
cout << mys.data[mys.top - 1];
cout << mys.data[mys.top] << endl;
elemtype x;
while (pop(mys,x))
{
cout << x;
}
}*/