一、堆栈
1.堆栈的顺序存储实现
//堆栈的实现
//堆栈的顺序储存
#define MaxSize <储存数据元素的最大个数>
typedef struct SNode *Stack;
struct SNode
{
ElementType Data[MaxSize]; //下标:0至MaxSize-1
int Top;
};
//创建堆栈
Stack CreateStack(int MaxSize)
{
Stack S=(Stack)malloc(sizeof(struct SNode));
S->Data=(ElementType *)malloc(MaxSize* sizeof(ElementType));
S->Top=-1;
S->MaxSize=MaxSize;
return S;
}
//入栈Push
void Push(Stack PtrS,ElementType item)
{
if(PtrS->Top== MaxSize-1)
{
printf("堆栈满");return;
}
else
{
PtrS->Data[++(PtrS->Top)]=item; //先加Top 再入栈
return;
}
}
//出栈 Pop
ElementType Pop(Stack PtrS)
{
if(PtrS->Top==-1)
{
printf("堆栈空");
return ERROR; //ERROR 标准错误
}
else
return(PtrS->Data[(PtrS->Top)--]);//先出栈 再减Top
}
2.堆栈的链式存储实现
栈的链式存储结构实际上就是一个单链表,叫做链栈.插入和删除操作只能在链栈的栈顶进行. 思考:栈顶指针Top应该在链表哪一头? 栈头,因为Pop操作要返回栈顶元素,对于单向链表找不到它的前一个结点。
typedef struct SNode *Stack;
struct SNode
{
ElementType Data;
struct SNode *Next;
}
Stack CreateStack()
{//构建一个堆栈的头结点,返回指针
Stack S=(Stack)malloc(sizeof(struct SNode));
S->Next=NULL;
return S;
}
//入栈Push
void Push(ElementType item,Stack S)//将元素item压入堆栈S
{
struct SNode *TmpCell;
TmpCell=(struct SNode *)malloc(sizeof(struct SNode));
TmpCell->Element=item;
TmpCell->Next=S->Next;
S->Next=TmpCell;
}
//出栈 Pop
ElementType Pop(Stack S)//删除并返回堆栈S的栈顶元素
{
struct SNode *FirstCell;
ElementType TopElem;
if(IsEmpty(S))
{
printf("堆栈空");
return NULL;
}
else
{
FirstCell=S->Next;
S->Next=FirstCell->Next;
TopElem=FirstCell->Element;
free(FirstCell);
return TopElem;
}
}
二、队列
1.普通队列的顺序存储实现
//一般Font和Rear先初始化为-1.当有元素入队,Rear向右移动一格(加1),
//放入队尾元素;当有元素出队,先将Font向右移动一格(加1),再删除队头元素
struct QNode
{
ElementType Data[MaxSize];
int rear;
int front;
};
typedef struct QNode *Queue;
2.循环队列的存储实现
随着入队出队的进行,会使整个队列整体向后移动,队尾的指针已经移到了最后,再有元素入队就会出现溢出,
而事实上此时队中并未真的满员,这种现象称为"假溢出"。所以引入了循环队列。
说明:循环队列少用了一个元素空间,把上图所示情况视为队列满。此时的状态是队尾指针加1就会从后面赶上队头指针,因此,队满的条件是:(Rear+1)%数组长度=Font。队空条件仍然是:Rear=Front。
//引入了循环队列,顺序存储可以定义为:
typedef int Position;
typedef struct QNode *PtrToQNode;
struct QNode
{
ElementType *Data;//存储元素的数组
Position Front,Rear;//队列的头尾指针
int MaxSize;//队列的最大容量
};
typedef PtrToQNode Queue;
//创建循环队列
Queue CreateQueue(int MaxSize)
{
Queue Q=(Queue)malloc(sizeof(struct QNode));
Q->Data=(ElementType *)malloc(MaxSize * sizeof(ElementType);
Q->Front=Q->Rear=0;
Q->MaxSize=MaxSize;
return Q;
}
//入队列
void AddQ(Queue PtrQ,ElementType item)
{
if((PtrQ->rear+1)%MaxSize==PtrQ->front)
{
printf("队列满");
return;
}
PtrQ->rear=(PtrQ->rear+1)%MaxSize;//有可能大于MaxSize,但是存储的话必须对其取余
PtrQ->Data[PtrQ->rear]=item;
}
//出队列
ElementType DeleteQ(Queue PtrQ)
{
if(PtrQ->front==PtrQ->rear)
{
print("队列空");
return ERROR;
}
else{
PtrQ->front=(PtrQ->front+1)%MaxSize;
return PtrQ->Data[PtrQ->front];
}
}