栈的顺序实现
顺序栈定义
const int maxsize=6;
typedef struct seqstack
{
DataType data[maxsize];
int top;
}SeqStk;
基本运算
1 初始化
int InitStack(SeqStk *stk)
{
stk-top=0;
return 1;
}
2 判栈空
int EmptyStack(SeqStk *stk)
//若栈为空,则返回值1,否则返回值0
{
if (stk->top==0)
return 1;
else
return 0;
}
3 进栈
int Push(SeqStk *stk,DataType x)
{//若栈未满,元素x进栈stk中,否则提示出错信息
if (stk-top == maxsize-1)
{
error("栈已满");
return 0;
}
else
{
stk->top++;
stk->data[stk-top]=x;
return 1;
}
}
4 出栈
int Pop(SeqStk *stk)
{
if (EmptyStack(stk))
{
error("下溢");
return 0;
}
else
{
stk-top--;
return 1;
}
}
5 取栈顶元素
DataType GetTop(SeqStk *stk)
{//取栈顶数据元素,栈顶数据元素通过参数返回
if (EmptyStack(stk))
return NULLData;
else
return stk->data[stk->top];
}
6 两栈相遇初始化
const int max=40;
typedef struct Dbstack
{
DataType data[max];
int top1,top2;
}DbStk;
两栈相遇时,top1=top2
判断上溢,top1+1=top2
当top1=0时栈1为空栈,top2=0时栈2 为空栈
栈的链接实现
链栈定义
typedef struct node
{
DataType data;
struct node *next;
}LkSk;
栈的基本运算在链栈上的实现算法
1 初始化
void InitStack(LkStk *LS)
{
LS=(LkStk *)malloc(sizeof(LkStk));
LS->next=NULL;//建立一个空栈
}
2 判栈空
int EmptyStack(LkStk *LS)
//若栈为空,则返回值1,否则返回值0
{
if (LS->next == NULL)
return 1;
else
return 0;
}
3 进栈-头插法
void Push(LkStk *LS,DataType x)
{
LkStk *temp;
temp=(LkStk *)malloc(sizeof(LkStk));
temp->data=x;
temp->next=LS->next;
LS->next=temp;
}
4 出栈
int Pop(LkStk *LS)
//栈顶数据元素通过参数返回,它的直接后继成为新的栈顶
{
LkStk *temp;
if (! EmptyStack(LS))
{
temp=LS->next;
LS->next=temp->next;
free(temp);
return 1;
}
else return 0;
}
5 取栈顶元素
DataType GetTop(LkStk *LS)
{
if ( !EmptyStack(LS))
return LS->next-data;
else return NULLData;
}
队列的顺序实现
定义顺序队列
const int maxsize=20;
typedef struct seqqueue
{
DataType data[maxsize];
int front,rear;
}SeqQue;
SeqQue SQ;
定义循环队列
ypedef struct cycqueue
{
DataType data[maxsize];
int front,rear;
}CycQue;
CycQue SQ;
循环队列的基本运算
1 队列的初始化
void InitQueue(CycQue CQ)
{
CQ.front=0;
CQ.rear=0;
}
2 判队列空
int EmptyQueue(CycQue CQ)
{
if (CQ.rear == CQ.front)
return 1;//队列空返回1
else return 0;
3 人队列
int EnQueue(CycQue CQ,DataType x)
{
if ((CQ.rear+1) % maxsize == CQ.front)
{
error(“队列满");
return 0;
}
else
{
CQ.rear=(CQ.rear+1)%maxsize;
CQ.data[CQ.rear]=x;
return 1;
}
}
4 出队列
int OutQueue(CycQue CQ)
{
if (EmptyQueue(CQ))
{
error(“队列空");
return 0;
}
else
{
CQ.front=(CQ.front+1)%maxsize;
return 1;
}
}
5 取队列首元素
DataType GetHead(CycQue CQ)
{
if (EmptyQueue(CQ))
return NULLData;
else
return CQ.data[(CQ.front+1)%maxsize];
}
原文:https://www.cnblogs.com/cnxm/p/14818978.html