链式队列的建立和一些简单的操作

链式就是链表,学习后面的,前面的链表还有线性表顺序表都要学好,这是基础!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//链式队列

typedef int data_t;
typedef struct node
{
	data_t data;
	struct node *next;
}linklist;

typedef struct kkkkk
{
	linklist *front;
	linklist *rear;
}lqueue;


//创建
lqueue *creatlqueue()
{
	lqueue *lq=(lqueue *)malloc(sizeof(lqueue));
	if(lq==NULL)
	{
		perror("malloc lqueue");
		return NULL;
	}

	lq->front=(linklist *)malloc(sizeof(linklist));

	lq->rear=lq->front;
	lq->front->next=NULL;

	//lq->front == head;

	return lq;
}

//判空

int lqueue_is_empty(lqueue *lq)
{
	return(lq->front==lq->rear)?1:0;
}

//求表长

int lqueue_length(lqueue *lq)
{
	linklist *p=lq->front->next;

	int len=0;
	while(p != NULL)
	{
		p=p->next;
		len++;
	}

	return len;
}


//入队
int lqueue_in(lqueue *lq,data_t data)
{
	linklist *new=(linklist *)malloc(sizeof(linklist));
	if(new==NULL)
	{
		perror("malloc lqueue");
		return -1;
	}

	new->next=NULL;
	new->data=data;

	lqueue*p=lq;

	p->rear->next=new;

	p->rear=new;       //栈的尾指针要移动到最后一个,new就是

	return 0;
}
	
//出队
data_t lqueue_out(lqueue *lq)
{
	if(lqueue_is_empty(lq))
		return -1;

	linklist *p=lq->front->next;

	data_t data=p->data;

	lq->front->next=p->next;

	if(lq->front->next==NULL)
		lq->rear=lq->front;

	free(p);
	p=NULL;

	return data;
}

//清空
int lqueue_clear(lqueue *lq)
{
	if(lqueue_is_empty(lq))
		return -1;

	linklist *p=lq->front->next;
	lq->front->next=NULL;
	lq->rear=lq->front;

	linklist *q=NULL;

	while(p!=NULL)
	{
		q=p->next;
		free(p);
		p=NULL;

		p=q;
	}
	return 0;
}

//销毁
void lqueue_xiaohui(lqueue **lq)
{
	lqueue_clear(*lq);

	free((*lq)->front);

	free(*lq);
	*lq=NULL;

}



//打印

void lqueue_printf(lqueue *lq)
{
	linklist *p=lq->front->next;
	while(p!=NULL)
	{
		printf("%d ",p->data);
		p=p->next;
	}

	puts("");

}

int main(int argc, const char *argv[])
{
	lqueue *lq=creatlqueue();
	if(lq==NULL)
		return -1;


	//入队
	int i=0;
	while(i<10)
	{
		lqueue_in(lq,i+1);
		i++;
	}
	
	lqueue_printf(lq);


	int m=lqueue_is_empty(lq);
	printf("%d\n",m);


	m=lqueue_length(lq);
	printf("m=%d\n",m);


	//出队
	int j=0;
	while(j<5)
	{
		data_t data = lqueue_out(lq);
		printf("data=%d \n",data);
		j++;
	}

	lqueue_printf(lq);


	//清空
	lqueue_clear(lq);

	lqueue_printf(lq);

	//销毁
	lqueue_xiaohui(&lq);
	lqueue_printf(lq);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值