3.1.栈
3.1.2 栈的存储结构和实现
顺序栈的C语言实现
#define STACK_INIT_SIZE 100;
#define STACKINCREMENT 10;
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
} SqStack;
顺序栈的基本操作实现
InitStack(&S)
Status InitStack(SqStack &S)
{
S.base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!S.base) exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
StackEmpty()
top = base;
Push(e):
*top++ = e
Status Push(SqStack &S, ElemType e)
{
if (S.top – S.base == S.stacksize) return ERROR;
*S.top = e;
S.top++;
return OK;
}
Pop(e):
e = *--top
Gettop():
e = *(top-1)
3.2.队列
3.2.2 队列的存储结构和实现
链队列的C语言实现
typedef struct QNode
{
QElemType data;
struct QNode *next;
} QNode, *QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
} LinkQueue;
链队列基本操作的实现
初始化
Status InitQueue(LinkQueue &Q)
{
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if (!Q.front) exit(OVERFLOW);
Q.front->next = NULL;
return OK;
}
入队
Status EnQueue(LinkQueue &Q, QElemType e)
{
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 DeQueue(LinkQueue &Q, QElemType &e)
{
if (Q.rear == Q.front) return ERROR;
p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if (Q.rear == p) Q.rear = Q.front;
free(p);
return OK;
}
循环队列的C语言实现
#define MAXSIZE 100
typedef struct
{
QElemType *base;
int front;
int rear;
} SqQueue;
循环队列基本操作的实现
初始化
Status InitQueue(SqQueue &Q)
{
Q.base = (QElemType *)malloc(MAXSIZE * sizeof(QElemType));
if (!Q.base) exit(OVERFLOW);
Q.front = Q.rear = 0;
return OK;
}
入队
Status EnQueue(SqQueue &Q, QElemType e)
{
if ((Q.rear + 1) % MAXSIZE == Q.front) return ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXSIZE;
return OK;
}
出队
Status DeQueue(SqQueue &Q, QElemType &e)
{
if (Q.front == Q.rear) return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;
return OK;
}