定义 队列是只允许在一端删除,在另一端插入的线性表 允许删除的一端叫做队头(front),允许插入的一端叫做队尾(rear)。 特性 先进先出(FIFO, First In First Out) 队列的主要操作 ADT Queue { //对象:由数据类型为QueueData的元素构成 int EnQueue (Queue *Q, QueueData x); //进队 int DeQueue (Queue *Q, QueueData &x);//出队 int GetFront (Queue *Q, QueueData &x);//取队头 void InitQueue (Queue *Q); //置空队 int QueueEmpty (Queue *Q); //判队空否 int QueueFull (Queue *Q); //判队满否 } 进队时队尾指针先进一 rear = rear + 1,再将新元素按rear 指示位置加入。 出队时队头指针先进一 front = front + 1,再将下标为front 的元素取出。 队满时再进队将溢出出错; 队空时再出队将队空处理。 #include <stdio.h>
#include <stdlib.h>
#define MAX 5
struct stack
{
int stack_text[MAX];
int top;
int buttom;
};
enum return_results{PUSH_OK, PUSH_NO, FULL_OK, FULL_NO, EMPTY_OK, EMPTY_NO};
typedef struct stack Stack;
void is_malloc_ok(Stack * stack)
{
if(stack == NULL)
{
printf("malloc error!\n");
exit(-1);
}
}
void create_stack(Stack ** stack)
{
*stack = (Stack *)malloc(sizeof(Stack));
is_malloc_ok(*stack);
}
void init_stack(Stack * stack)
{
stack->top = -1;
stack->buttom = -1;
}
int is_full(Stack * stack)
{
if(stack -> buttom == -1)
{
if(stack -> top == MAX - 1)
{
return FULL_OK;
}
}
else if((stack -> top - stack -> buttom + 1) == MAX)
{
return FULL_OK;
}
return FULL_NO;
}
int push_stack(Stack * stack, int num)
{
int i = 0;
if(is_full(stack) == FULL_OK)
{
printf("stack is full!\n");
return PUSH_NO;
}
if(stack -> top < (MAX - 1))
{
stack -> top++;
stack ->stack_text[stack -> top] = num;
}
else
{
for(i = stack -> buttom; i <= stack -> top; i++)
{
stack -> stack_text[i - stack -> buttom] = stack -> stack_text[i];
}
stack -> top = stack -> top - stack -> buttom - 1;
stack -> buttom = 0;
stack -> stack_text[stack -> top] = num;
}
return PUSH_OK;
}
int is_empty(Stack * stack)
{
if(stack -> top <= stack -> buttom)
{
return EMPTY_OK;
}
return EMPTY_NO;
}
int pop_stack(Stack * stack)
{
if(is_empty(stack) == EMPTY_OK)
{
printf("the stack is empty!\n");
return EMPTY_OK;
}
return stack -> stack_text[++(stack -> buttom)];
}
int main()
{
int i = 0;
int num = 0;
Stack * stack = NULL;
create_stack(&stack);
init_stack(stack);
for(i = 0; i < MAX; i++)
{
if(push_stack(stack, i + 1) == PUSH_OK)
{
printf("push ok!\n");
}
}
for(i = 0; i < MAX; i++)
{
num = pop_stack(stack);
printf("the num is %d\n", num);
}
return 0;
}
|