棧的定義
僅在表尾進(jìn)行插入刪除操作的線性表
棧的抽象數(shù)據(jù)類型
棧的線性存儲(chǔ)結(jié)構(gòu)
using namespace std;
typedef int SElemType;
#define INIT_SIZE 10
typedef struct
{
SElemType *base;//棧底指針蚜锨,在棧構(gòu)造之前和之后銷毀犯助,base值為NULL
SElemType *top;//棧頂指針
int stacksize;
}SqStack;
void InitStack(SqStack &s, int init_size) {
s.base = (SElemType *)malloc(sizeof(SElemType) * init_size);
if (!s.base)
{
exit(0);
}
s.top = s.base;
s.stacksize = init_size;
}
void DestroyStack(SqStack &s) {
free(s.base);
s.base = NULL;
s.top = NULL;
s.stacksize = 0;
}
void ClearStack(SqStack &s) {
s.top = s.base;
}
int StackEmpty(SqStack s) {
if (s.top == s.base) {
return 1;
}
else
return 0;
}
SElemType GetTop(SqStack s, SElemType &e) {
if (s.top == s.base)
{
exit(0);
}
e = *(s.top - 1);
return e;
}
SqStack Push(SqStack &s, SElemType e) {
if (s.top - s.base >= s.stacksize) { //若棧滿
s.base = (SElemType *)realloc(s.base, (s.stacksize + 10) * sizeof(SElemType)); //重新分配空間
if (!s.base)
exit(0);
s.top = s.base + s.stacksize;
s.stacksize += 10;
}
*s.top++ = e;
return s;
}
SqStack Pop(SqStack &s, SElemType &e) {
if (s.top == s.base)
exit(0);
e = *--s.top;
return s;
}
void StackTreaverse(SqStack s) {
while (s.top > s.base)
{
cout << *s.base++ << " ";
}
cout << endl;
}
兩棧共享空間
typedef int SElemType;
#define MAXSIZE 20
using namespace std;
typedef struct{
SElemType data[MAXSIZE];
SElemType top1;
SElemType top2;
}SqDoubleStack;
SqDoubleStack Push(SqDoubleStack *s, int e, int StackNumber) {
if(s->top1 + 1 == s->top2)
{
printf("棧滿!\n");
exit(0);
}
if (StackNumber == 1)
{
s->data[++s->top1] = e;
}
else if (StackNumber == 2)
{
s->data[--s->top2] = e;
}
return *s;
}
SqDoubleStack Pop(SqDoubleStack *s, int *e, int StackNumber)
{
if (StackNumber == 1)
{
if (s->top1 == -1)
{
printf("棧1是空棧宪摧!\n");
exit(0);
}
*e = s->data[s->top1--];
}
else if (StackNumber == 2)
{
if (s->top2 == MAXSIZE)
{
printf("棧2是空棧!\n");
exit(0);
}
*e = s->data[s->top2++];
}
return *s;
}
棧的鏈?zhǔn)酱鎯?chǔ)結(jié)構(gòu)
typedef int SElemType;
typedef struct StackNode {
SElemType data;
struct StackNode *next;
}StackNode, *LinkStackPtr;
typedef struct LinkStack {
LinkStackPtr top;
int count;
}LinkStack;
LinkStack Push(LinkStack *S, SElemType e) {
LinkStackPtr s = (LinkStackPtr)malloc(sizeof(StackNode));
s->data = e;
s->next = S->top;
S->top = s;
S->count++;
return *S;
}
LinkStack Pop(LinkStack *S, SElemType *e) {
LinkStackPtr p;
*e = S->top->data;
p = S->top;
S->top = S->top->next;
free(p);
S->count--;
return *S;
}