堆栈:只在一端(栈顶)做操作,后入先出
顺序栈:
首先对堆栈的结构体作定义
#define stack_size 100
#define stack_increment 10
typedef struct _SNode {
int* base;//若base为NULL则栈不存在
int* top;//栈顶与栈底初始位置相同,且栈顶指针始终指向栈顶元素的下一个位置
int stacksize;
}Stack;
构建栈
int InitStack(Stack* s) {
s->base = (int*)malloc(stack_size * sizeof(Stack));
if (!(s->base))
exit(0);
s->top = s->base;
s->stacksize = stack_size;
return 1;
}
销毁栈
int DestroyStack(Stack* s)
{
free(s);
s->top = s->base = NULL;
s->stacksize = 0;
return 1;
}
入栈
int Push(Stack* s, int *e)
{
if (s->top - s->base >= s->stacksize) {
s->base = (int*)realloc(s->base, sizeof(Stack*) * (s->stacksize + stack_increment));
s->top = s->base + s->stacksize;
s->stacksize = s->stacksize + stack_increment;
}
*s->top++ = *e;
return 1;
}
出栈
int Pop(Stack* s, int e)
{
if (s->base == s->top){
printf("Stack is empty");
}
e = *s->top--;
return 1;
}
得到栈顶元素
int getStack(Stack* s, int *e)
{
if (s->base == s->top)
printf("stack is empty");
*e = *s->top--;
return 1;
}
队列:
先进先出
链式队列:类似链表
循环队列:
对其结构体定义
#define MAXSIZE 100
typedef struct _QNode {
int front;
int rear;
int *base;
}Queue;
当队列未满而front、rear指针指向队列末尾时,若分配空间已确定,则不能插入新的队尾元素。此时可以将队列塑造为环状空间,代码与循环栈类似,需要注意返回队列长度时,由于rear、front指针前后位置不确定,应返回(Q.rear-Q.front+MAXSIZE)%MAZSIZE
int InitQueue(Queue *q) {
q->base = (int*)malloc(sizeof(Queue) * MAXSIZE);
q->front = q->rear = 0;
return 1;
}
int DestroyQueue(Queue* q)
{
free(q->base);
q->base = NULL;
q->front = q->rear = 0;
return 1;
}
int Queuelength(Queue* q) {
return (q->rear - q->front + MAXSIZE - 1) % MAXSIZE;
}
int enQueue(Queue* q, int e) {
if ((q->rear + 1) % MAXSIZE == q->front) {
prinf("FULL");
return 0;
}
q->base[q->rear] = e;//rear与front都是从0开始
q->rear = (q->rear + 1) / MAXSIZE;
return 1;
}
int deQueue(Queue* q, int e) {
if (q->front == q->rear) {
printf("empty");
return 0;
}
e = q->base[q->front];
q->front = (q->front + 1) / MAXSIZE;
return 1;
}