链式队列的基础操作
队列概念:
队列是限制在两端进行插入操作和删除操作的线性表,允许进行存入操作的一端称为“队尾”,允许进行删除操作的一端称为“队头”。当线性表中没有元素时,称为“空队”。特点 :先进先出(FIFO)。
队列的特征:
特殊的线性表,先进先出(FIFO)。
1)数据:
对于非空的队列,表头没有直接前驱,表尾没有直接后继,其它有且仅有一个直接前驱和一个直接后继。
2)操作:
只允许在表尾插入数据,在表头删除数据
#ifndef __LINKQUEUE_H__
#define __LINKQUEUE_H__
#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
typedef int data_t;
typedef struct LinkQueueNode
{
data_t data;
struct LinkQueueNode *next;
}queuenode,*pqueuenode;
typedef struct LinkQueue
{
pqueuenode front,rear;
}linkqueue,*plinkqueue;
extern void init_linkqueue(plinkqueue *H);
extern bool is_empty_linkqueue(plinkqueue h);
extern void in_linkqueue(plinkqueue h,data_t val);
extern void out_linkqueue(plinkqueue h,data_t *val);
extern void show_linkqueue(plinkqueue h);
#endif
#include "linkqueue.h"
//初始化
void init_linkqueue(plinkqueue *H)
{
*H = (plinkqueue)malloc(sizeof(linkqueue));
if(NULL == *H)
{
perror("Malloc failed");
exit(-1);
}
(*H)->front = (pqueuenode)malloc(sizeof(queuenode));
if(NULL == (*H)->front)
{
perror("Malloc failed");
exit(-1);
}
(*H)->front->next = NULL;
(*H)->rear = (*H)->front;
}
//判断链表是否为空
bool is_empty_linkqueue(plinkqueue h)
{
//相等为空
if(h->front == h->rear)
return true;
else
return false;
}
//入队
void in_linkqueue(plinkqueue h,data_t val)
{
pqueuenode p;
p = (pqueuenode)malloc(sizeof(queuenode));
if(NULL == p)
{
perror("Malloc failed");
exit(-1);
}
p->data = val;
p->next = h->rear->next;
h->rear->next = p;
h->rear = p;
printf("%p %p\n",h->front,h->rear);
}
//出队
void out_linkqueue(plinkqueue h,data_t *val)
{
pqueuenode p;
//判断是否尾空链表
if(is_empty_linkqueue(h))
{
printf("The linkqueue is empty\n");
return ;
}
//p = h->front;
//h->front = h->front->next;
//*val = h->front->data;
p = h->front;
h->front = p->next;
*val = p->next->data;
printf("%d\n",*val);
free(p);
}
//打印队列
void show_linkqueue(plinkqueue h)
{
pqueuenode p;
for(p=h->front->next;p!=NULL;p=p->next)
printf("%d ",p->data);
puts("");
}
#include "linkqueue.h"
int main(int argc, const char *argv[])
{
plinkqueue H;
data_t in_val,out_val;
init_linkqueue(&H);
while(1)
{
printf("Please input:");
if(scanf("%d",&in_val) == 1)
{
in_linkqueue(H,in_val);
show_linkqueue(H);
}
else
{
out_linkqueue(H,&out_val);
show_linkqueue(H);
while(getchar() != '\n');
}
}
return 0;
}