栈和队列的定义
栈是只允许在固定的一端进行插入和删除元素操作的线性表,进行插入和删除的一端称作栈顶,另一端为栈底。
栈通常使用顺序表进行实现,便于在栈顶top进行插入删除操作
typedef struct stack
{
SDataType * array;
int capacity;//栈的容量
int top;//栈顶下标
}Stack;
队列是只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out)
入队列:进行插入操作的一端称为队尾rear
出队列:进行删除操作的一端称为队头front
typedef struct node
{
QDataType data;
struct node* next;
}node;
typedef struct Queue
{
node* front;
node* rear;
}Queue;
栈的初始化
void StackInit(Stack* st,int capacity)
{
assert(st);
st->array = (SDataType*)malloc(sizeof(SDataType)*capacity);
if (st->array)
{
st->capacity = capacity;
st->top = 0;
}
}
入栈
Stack *Capacity(Stack* st)//对栈进行扩容
{
int newcapacity = st->capacity * 2;
SDataType* temp = (SDataType*)malloc(sizeof(SDataType) * newcapacity);//申请一个二倍大的空间
if (temp == NULL)
return NULL;
memcpy(temp, st->array, sizeof(SDataType) * st->capacity);//将旧栈中的数据拷贝进新栈
free(st->array);
st->array = temp;
st->capacity = newcapacity;
return st;
}
void StackPush(Stack* st,SDataType x)、、入栈
{
assert(st);
if (st->capacity == st->top)
st=Capacity(st);//栈满需对栈进行扩容
st->array[st->top] = x;
st->top++;
}
出栈
void StackPop(Stack* st)
{
if (StackEmpty(st))
printf("出栈出错");
st->top--;
}
判断栈空
int StackEmpty(Stack* st)
{
if (st->top == 0)
return 1;
else return 0;
}
销毁栈
void StackDestroy(Stack* ps)
{
assert(ps);
if (ps->array)
{
free(ps->array);
ps->capacity = 0;
ps->top = 0;
}
}
初始化队列
队列通常用带头节点的链表进行实现,方便在队头进行删除操作
void QueueInit(Queue* q)
{
q->front =(node*)malloc(sizeof(node));
if (q->front)
{
q->rear = q->front;
q->front->next = NULL;
q->front->data = 0;
}
}
队尾入队列
void QueuePush(Queue* q, QDataType data)
{
node *p = (node*)malloc(sizeof(node));
if (p == NULL)
return;
else {
p->data = data;
q->rear->next = p;
q->rear = p;
q->rear->next = NULL;
}
}
队头出队列
QDataType QueuePop(Queue* q)
{
assert(q);
QDataType ret = q->front->next->data;
if (!QueueEmpty(q))
{
node* p = q->front->next;
q->front->next = p->next;
//队列中只有一个元素
if (p == q->rear)
q->rear = q->front;
free(p);
}
return ret;
}
获取队列队尾元素
QDataType QueueBack(Queue* q)
{
assert(q);
return q->rear->data;
}
判断队列空
int QueueEmpty(Queue* q)
{
assert(q);
if (q->front == q->rear)
return 1;
else return 0;
}
销毁队列
void QueueDestroy(Queue* q)
{
assert(q);
node* p = q->front->next;
while (p)
{
q->front->next = p->next;
free(p);//将队列中的每个节点释放
p = q->front->next;
}
free(q->front);
q->front = q->rear = NULL;
}