1、预定义常量、数据结构表示、数据元素类型
函数结果状态代码
#define FALSE 0
#define ERROR 0
#define OVERFLOW -2
#define OK 1
#define INFEASIBLE -1
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
数据结构表示用typedef描述,数据元素类型约定为ElemType
typedef struct
{
int data;
}Node;
typedef int Status;
typedef Node ElemType;
typedef Node QElemType;
typedef struct
{
ElemType* base; //栈底指针
ElemType* top; //栈顶指针
int stacksize;
} SqStack;
typedef struct Qnode
{
QElemType data;
struct Qnode* next;
}Qnode, * QueuePtr;
typedef struct
{
QueuePtr front;//队头
QueuePtr rear;//队尾
} LinkQueue;
2、栈和队列的基本操作函数
(1)顺序栈部分基本操作
Status InitStack(SqStack& S, int n1)
{//顺序栈的初始化
S.base = (ElemType*)malloc(n1 * sizeof(ElemType));
if (!S.base) exit(OVERFLOW);
S.top = S.base;
S.stacksize = n1;
return OK;
}
Status Push(SqStack& S, ElemType e)
{//入顺序栈
if (S.top - S.base < S.stacksize)
{
*S.top = e;
S.top++;
return OK;
}
else
{
cout << "栈已满!" << endl;
return ERROR;
}
}
Status Pop(SqStack& S, ElemType& e)
{//退栈
if (S.top == S.base) return ERROR; //空栈
S.top--;
e = *S.top;
return OK;
}
Status isfull(SqStack& S)
{//判断栈是否满
return (S.top - S.base >= S.stacksize);
}
Status GetTop(SqStack S, ElemType& e)
{//获得顺序栈栈顶元素
if (S.top == S.base) return ERROR;//空栈
e = *(S.top - 1);
return OK;
}
Status StackEmpty(SqStack S)
{//判断空栈
return (S.top == S.base);
}
(2)队列部分基操
Status InitQueue(LinkQueue& Q)
{//栈初始化
Q.front = Q.rear = (QueuePtr)malloc(sizeof(Qnode));
if (!Q.front) exit(OVERFLOW);
Q.front->next = NULL;
return OK;
}
Status DeQueue(LinkQueue& Q, QElemType& e)
{//队首元素出队
if (Q.front == Q.rear) return ERROR;
QueuePtr P = Q.front->next;
e = P->data;
Q.front->next = P->next;
if (Q.rear == P) Q.rear = Q.front;
free(P);
return OK;
}
Status EnQueue(LinkQueue& Q, QElemType e)
{//队尾入队
QueuePtr P = (QueuePtr)malloc(sizeof(Qnode));
if (!P) exit(OVERFLOW);
P->data = e;
P->next = NULL;
Q.rear->next = P;
Q.rear = P;
return OK;
}
Status QueueEmpty(LinkQueue& Q)
{//判断空队列
return (Q.front == Q.rear);
}