目录
1.结构体定义
typedef struct link{
datatype data;
struct link *next;
} link_t,*plink_t;
typedef struct HT{
plink_t head;
plink_t tail;
}HT_t,*pHT_t;
2. 队列的初始化
/**
***************************************
*@brief : 队列的初始化
*@param :None
*@retval :pHT_t
***************************************
*/
pHT_t queue_init(void)
{
plink_t node = (plink_t)malloc(sizeof(link_t));
if(node==NULL){
perror("malloc plink_t node error");
return NULL;
}
node->next = NULL;
pHT_t p = (pHT_t)malloc(sizeof(HT_t));
if(p==NULL){
perror("malloc pHT_t p error");
return NULL;
}
p->head = node;
p->tail = node;
return p;
}
3.入队
/**
***************************************
*@brief : 入队
*@param :p 队列
*@param :d 数据
*@retval :int 成功返回0 失败返回-1
***************************************
*/
int enqueue(pHT_t p,datatype d)
{
//创建新的结点
plink_t node = (plink_t)malloc(sizeof(link_t));
if(node==NULL){
perror("malloc plink_t node error");
return -1;
}
//给新的结点属性赋值
node->data = d;
//将新的结点插入到 tail的后面
node->next = p->tail->next;
p->tail->next = node;
// 将tail 指向 新的结点
p->tail = node;
return 0;
}
4.出队
/**
***************************************
*@brief : 出队
*@param :p 队列
*@param :d 数据
*@retval :int 成功返回0 失败返回-1
***************************************
*/
int dequeue(pHT_t p,datatype *d)
{
//判断是否 队 空
if(p->head == p->tail){
printf("sorry!队空\n");
return -1;
}
//保存当前 队头 结点
plink_t node = p->head;
// 队头往后移动一个
p->head = p->head->next;
// 将此是 队头指向的结点 的数据域 出队
*d = p->head->data;
// 将原来保存的结点释放
free(node);
return 0;
}
5.遍历
/**
***************************************
*@brief : 遍历
*@param :p 队列
*@param :d 数据
*@retval :int 成功返回0 失败返回-1
***************************************
*/
void display(pHT_t p)
{
plink_t node = p->head;
printf("遍历结果为:\n");
while(node!=p->tail){
printf("| %d |\n",node->next->data);
node = node->next;
}
printf("\n");
}
6.测试--正数入队,负数出队
int main(void)
{
pHT_t p = queue_init();
if(p==NULL)
return -1;
printf("%p\n",p);
//正数入队,负数出队
datatype d;
int ret;
while(1)
{
ret = scanf("%d",&d);
if(ret==0)
break;
if(d>0){
enqueue(p,d);
}else if(d<0){
if(!dequeue(p,&d))
printf("%d出队了\n",d);
}
display(p);
}
return 0;
}