链式就是链表,学习后面的,前面的链表还有线性表顺序表都要学好,这是基础!
#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;
}