顺序栈
#include<stdio.h>
#include<iostream>
#include<assert.h>
#define INT_SIZE 10
using namespace std;
//顺序栈
typedef struct stack
{
int* base;
int top;//待入的地方
int stacksize;//容量
}Stack,*Psatck;
void Init(Stack* ps)
{
ps->base = (int*)malloc(sizeof(int)*INT_SIZE);
assert(ps->base != NULL);
ps->top = 0;
ps->stacksize = INT_SIZE;
}
bool Isempty(Stack* ps)
{
return ps->top == 0;
}
bool Isfull(Stack* ps)
{
return ps->top == ps->stacksize;
}
void Inc(Stack* ps)
{
ps->base = (int*)realloc(ps->base,sizeof(int) * ps->stacksize * 2);//两个参数,一个为之前的地址,另一个是最后一共需要的空间大小
assert(ps->base != NULL);
ps->stacksize *= 2;
}
bool Push(Stack* ps,int val)
{
//需要判满
assert(ps != NULL);
if (Isfull(ps))
{
Inc(ps);
}
ps->base[ps->top++] = val;
return true;
}
bool Pop(Stack* ps,int* rtval)
{
assert(ps != NULL);
if (Isempty(ps))
{
return false;
}
*rtval = ps->base[--ps->top];
return true;
}
//获取栈顶元素
bool Top(Stack* ps, int* rtval)
{
assert(ps != NULL);
if (Isempty(ps))return false;
*rtval = ps->base[ps->top - 1];
return true;
}
int GetLength(Stack* ps)
{
return ps->top;
}
void Clear(Stack* ps)
{
ps->top = 0;
}
void Destroy(Stack* ps)
{
free(ps->base);
ps->base = NULL;
}
void Show(Stack* ps)
{
for (int i = 0; i < ps->top; ++i)
{
printf("%d ", ps->base[i]);
}
}
int main()
{
Stack st;
Init(&st);
for (int i = 0; i < 20; ++i)
{
Push(&st, i + 1);
}
Show(&st);
int rtval;
Top(&st, &rtval);
printf("%d\n", rtval);
int tmp;
Pop(&st, &tmp);
printf("%d\n", tmp);
Show(&st);
return 0;
}
链式栈
#include<stdio.h>
#include<iostream>
#include<assert.h>
using namespace std;
typedef struct SNode
{
int data;
SNode* next;
}SNode,*PSNode;
void Init(SNode* ps)
{
ps->next = NULL;
}
SNode* BuyNode()
{
SNode* s = (SNode*)malloc(sizeof(SNode));
memset(s, 0, sizeof(SNode));
return s;
}
void Push(SNode* ps,int val)
{
SNode* p = BuyNode();
p->data = val;
p->next = ps ->next;
ps->next = p;
}
bool Pop(SNode* ps,int* rtval)
{
assert(ps != NULL);
if (ps->next != NULL)
{
SNode* p = ps->next;
ps->next = ps->next->next;
*rtval = p->data;
return true;
}
return false;
}
bool Top(SNode* ps,int* rtval)
{
assert(ps != NULL);
if (ps->next != NULL)
{
SNode* p = ps->next;
*rtval = p->data;
return true;
}
return false;
}
void Clear(SNode* ps)
{
SNode* p = ps->next;
SNode* q = NULL;
for (p; p!= NULL; p = p->next)
{
q = p;
free(q);
}
}
int main()
{
SNode st;
Init(&st);
int rtval;
for (int i = 0; i < 10; ++i)
{
Push(&st, i);
}
Top(&st, &rtval);
printf("%d",rtval);
}