链队列的相关操作

目录

1.结构体定义

2. 队列的初始化

3.入队

4.出队

5.遍历

6.测试--正数入队,负数出队


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;
}


 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值