顺序栈
#pragma once
//顺序栈,栈顶在尾部
#define INIT_SIZE 10
typedef struct Stack
{
int *elem;
int top;
int stacksize;
}Stack,*PStack;
//初始化
void InitStack(PStack ps);
//入栈
bool Push(PStack ps,int val);
//栈是否为空
bool IsEmpty(PStack ps);
//获取栈顶元素的值,但不删除
//rtval:输出参数
bool GetTop(PStack ps,int *rtval);
//出栈,得到栈顶值,并删除
bool Pop(PStack ps,int *rtval);
void Destroy(PStack ps);
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "stack.h"
//初始化
void InitStack(PStack ps)
{
assert(ps!=NULL);
ps->elem=(int *)malloc(INIT_SIZE*sizeof(int));
ps->top=0;
ps->stacksize=INIT_SIZE;
}
static bool IsFull(PStack ps)
{
return ps->top==ps->stacksize;
}
//入栈
static void Inc(PStack ps)
{
ps->elem=(int *)realloc(ps->elem,ps->stacksize*2*sizeof(int));
ps->stacksize*=2;
}
bool Push(PStack ps,int val)
{
if(IsFull(ps))
{
Inc(ps);
}
ps->elem[ps->top++]=val;
return true;
}
//栈是否为空
bool IsEmpty(PStack ps)
{
return ps->top==0;
}
//获取栈顶元素的值,但不删除
//rtval:输出参数
bool GetTop(PStack ps,int *rtval)
{
if(IsEmpty(ps))
{
return false;
}
if(rtval!=NULL)
{
*rtval=ps->elem[ps->top-1];
}
return true;
}
//出栈,得到栈顶值,并删除
bool Pop(PStack ps,int *rtval)
{
if(IsEmpty(ps))
{
return false;
}
if(rtval!=NULL)
{
*rtval=ps->elem[ps->top-1];
}
--ps->top;
return true;
}
void Destroy(PStack ps)
{
free(ps->elem);
ps->elem=NULL;
ps->top=0;
ps->stacksize=0;
}
#include <stdio.h>
#include "stack.h"
int main()
{
Stack s;
InitStack(&s);
for(int i=0;i<10;i++)
{
Push(&s,i);
}
int val;
while(!IsEmpty(&s))
{
Pop(&s,&val);
printf("%d ",val);
}
printf("\n");
Destroy(&s);
return 0;
}
链式栈
#pragma once
//带头结点的链式栈,栈顶在第一个数据节点
typedef struct SNode
{
int data;
struct SNode *next;
}SNode,*PStack;
//初始化
void InitStack(PStack ps);
//入栈
bool Push(PStack ps,int val);
//栈是否为空
bool IsEmpty(PStack ps);
//获取栈顶元素的值,但不删除
//rtval:输出参数
bool GetTop(PStack ps,int *rtval);
//出栈,得到栈顶值,并删除
bool Pop(PStack ps,int *rtval);
void Destroy(PStack ps);
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "lstack.h"
//初始化
void InitStack(PStack ps)
{
assert(ps!=NULL);
if(ps==NULL)
{
return ;
}
ps->next=NULL;
}
//入栈
bool Push(PStack ps,int val)
{
SNode *p=(SNode *)malloc(sizeof(SNode));
p->data=val;
p->next=ps->next;
ps->next=p;
return true;
}
//栈是否为空
bool IsEmpty(PStack ps)
{
return ps->next==NULL;
}
//获取栈顶元素的值,但不删除
//rtval:输出参数
bool GetTop(PStack ps,int *rtval)
{
if(IsEmpty(ps))
{
return false;
}
if(rtval!=NULL)
{
*rtval=ps->next->data;
}
return true;
}
//出栈,得到栈顶值,并删除
bool Pop(PStack ps,int *rtval)
{
if(IsEmpty(ps))
{
return false;
}
SNode *p=ps->next;
if(rtval!=NULL)
{
*rtval=p->data;
}
ps->next=p->next;
free(p);
return true;
}
void Destroy(PStack ps)
{
SNode *p;
while(ps->next!=NULL)
{
p=ps->next;
ps->next=p->next;
free(p);
}
}
#include <stdio.h>
#include "lstack.h"
int main()
{
SNode s;
InitStack(&s);
for(int i=0;i<20;i++)
{
Push(&s,i);
}
int tmp;
while(!IsEmpty(&s))
{
Pop(&s,&tmp);
printf("%d ",tmp);
}
printf("\n");
return 0;
}