栈和队列的实现,咕咕咕
1.栈的实现
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int st;
typedef struct stack
{st* data;int top;int capacity;
}stack;
//检查扩容
void checkcapacity(stack* ps)
{if(ps->top==ps->capacity){int newcapacity=ps->capacity==0?4:ps->capacity*2;st* tmp=(st*)realloc(ps->data,newcapacity*sizeof(st));if(tmp==NULL){perror("tmp realloc");exit(1);}ps->data=tmp;ps->capacity=newcapacity;}
}
//初始化栈
void stackinit(stack* ps)
{ps->data=NULL;ps->top=ps->capacity=0;
}
//入栈
void stackpush(stack* ps,st x)
{assert(ps);checkcapacity(ps);ps->data[ps->top]=x;ps->top++;
}
//出栈
void stackpop(stack* ps)
{
assert(ps->top>0);
ps->top--;
}
//获取栈顶元素
st stacktop(stack* ps)
{assert(ps->top>0);return ps->data[ps->top-1];
}
//获取有效元素
int stacksize(stack* ps)
{return ps->top;
}
//判断是否为空
int stackempty(stack* ps)
{return ps->top==0;
}
//销毁栈
void stackdestroy(stack* ps)
{assert(ps->data);free(ps->data);ps->capacity=ps->top=0;
}
2.队列的实现
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int qt;
typedef struct qlistnode
{qt data;struct qlistnode* next;
}qnode;
typedef struct queue
{qnode* head;qnode* tail;int count;
}queue;
//初始化节点
qnode* buynode(qt x)
{qnode* newnode=(qnode*)malloc(sizeof(qnode));if(newnode==NULL){perror("newnode malloc");exit(1);}newnode->data=x;newnode->next=NULL;
}
//判断是否为空
int queueempty(queue* q)
{return q->head==NULL;
}
//初始化队列
void queueinit(queue* q)
{q->head=NULL;q->tail=NULL;q->count=0;
}
//队尾入队
void queuepush(queue* q,qt x)
{qnode* newnode=buynode(x);if(queueempty(q)){q->head=newnode;q->tail=newnode;}else{q->tail->next=newnode;q->tail=newnode;}q->count++;
}
//队头出队
void queuepop(queue* q)
{assert(!queueempty(q));qnode* tmp=q->head;q->head=q->head->next;if(q->head==NULL){q->tail==NULL;}free(tmp);q->count--;
}
//获取对头部元素
qt queuefront(queue* q)
{assert(!queueempty(q));return q->head->data;
}
//获取队尾元素
qt queueback(queue* q)
{assert(!queueempty(q));return q->tail->data;
}
//获取队列元素数量
int queuecount(queue* q)
{return q->count;
}
//销毁队列
void queuedestroy(queue* q)
{while(!queueempty(q)){queuepop(q);}
}