Queue *pQueue, QueueElemType *e)
{
if (IsQueueEmpty(*pQueue))
{
printf("队列为空,不能执行退队操作\n");
return ERROR;
}
else
{
*e = pQueue->base[pQueue->front];
pQueue->front = (pQueue->front + 1) % MAX_QUEUE_SIZE;
return OK;
}
}
[cpp]
栈头文件:
#ifndef STACK_H
#define STACK_H
#include
#include "BinaryTree.h"
//
// 栈的头文件声明部分:Stack.h
// 栈初始容量
#define STACK_INIT_SIZE 20
// 栈容量不够用时,栈的增量
#define STACK_SIZE_INCREMENT 10
typedef BTree StackElemType;
//
// 顺序栈结构体
typedef struct tagStack
{
StackElemType *base; // 指向栈底
StackElemType *top; // 指向栈顶
int stackSize; // 栈的大小
}Stack;
//
// 初始化栈
int InitStack(Stack *s);
//
// 销毁栈
void DestroyStack(Stack *s);
//
// 入栈
void Push(Stack *s, StackElemType e);
//
// 出栈
void Pop(Stack *s, StackElemType *e);
//
// 判断栈是否为空
int IsStackEmpty(Stack s);
//
// 取栈顶元素
int GetTop(Stack s, StackElemType *e);
#endif
栈头文件:
#ifndef STACK_H
#define STACK_H
#include
#include "BinaryTree.h"
//
// 栈的头文件声明部分:Stack.h
// 栈初始容量
#define STACK_INIT_SIZE 20
// 栈容量不够用时,栈的增量
#define STACK_SIZE_INCREMENT 10
typedef BTree StackElemType;
//
// 顺序栈结构体
typedef struct tagStack
{
StackElemType *base; // 指向栈底
StackElemType *top; // 指向栈顶
int stackSize; // 栈的大小
}Stack;
//
// 初始化栈
int InitStack(Stack *s);
//
// 销毁栈
void DestroyStack(Stack *s);
//
// 入栈
void Push(Stack *s, StackElemType e);
//
// 出栈
void Pop(Stack *s, StackElemType *e);
//
// 判断栈是否为空
int IsStackEmpty(Stack s);
//
// 取栈顶元素
int GetTop(Stack s, StackElemType *e);
#endif
[cpp]
栈实现文件:
//
// 顺序栈的实现文件:Stack.c
#include
#include
#include "Stack.h"
//
// 初始化栈
int InitStack(Stack *s)
{
s->base = (StackElemType *)malloc(sizeof(StackElemType) * STACK_INIT_SIZE);
if (!s->base) // 申请栈内存失败
{
exit(OVERFLOW);
}
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
return OK;
}
//
// 销毁栈
void DestroyStack(Stack *s)
{
if (s != NULL)
{
free(s->base);
s->top = NULL;
s->base = NULL;
s->stackSize = 0;
}
}
//
// 入栈
void Push(Stack *s, StackElemType e)
{
StackElemType *tmp;
if (s->top - s->base >= s->stackSize) // 栈已经满
{
tmp = (StackElemType *)realloc(s->base, (STACK_SIZE_INCREMENT + s->stackSize)
* sizeof(StackElemType));
if (!tmp)
{
exit(OVERFLOW); // 重新分配失败则退出
}
s->base = tmp;
s->top = s->base + s->stackSize;
s->stackSize += STACK_SIZE_INCREMENT;
}
*(s->top) = e;
s->top++;
}
//
// 出栈
void Pop(Stack *s, StackElemType *e)
{
if (s->top == s->base) // 如果栈为空栈
{
return;
}
*e = *(--s->top);
}
//
// 判断栈是否为空
// 返回非0表示空
int IsStackEmpty(Stack s)
{
return !(s.top - s.base);
}
//
// 取栈顶元素
int GetTop(Stack s, StackElemType *e)
{
if (!IsStackEmpty(s))
{
*e = *(s.top - 1); // 此处出错,原因?
return OK;
}
else
{
return ERROR;
}
}
栈实现文件:
//
// 顺序栈的实现文件:Stack.c
#include
#include
#include "Stack.h"
//
// 初始化栈
int InitStack(Stack *s)
{
s->base = (StackElemType *)malloc(sizeof(StackElemType) * STACK_INIT_SIZE);
if (!s->base) // 申请栈内存失败
{
exit(OVERFLOW);
}
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
return OK;
}
//
// 销毁栈
void DestroyStack(Stack *