C语言--队列

来源:互联网 发布:优盘 启动 windows pe 编辑:程序博客网 时间:2024/06/08 06:04

      队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。

       队列的实现可以使用链表和数组,这里采用单链表的形式来实现队列。

1.定义一个单链表和一个队列

typedef struct _Node
{
int data;
struct _Node *next;
}node;//这里定义了一个链表

typedef struct _Queue
{
node *front;
node *rear;
}queue;//这里定义了一个队列,有队头和队尾指针

2.创建一个空的队列

   1.分配一片内存

   2.使头指针和尾指针都指向NULL;

queue *creatqueue()
{
queue *q=(queue *)malloc(sizeof(queue));
q->front=NULL;
q->rear=NULL;
}

3.入队操作

队列的入队需要从队尾入队

    1.为一个新的节点分配内存,并存储号需要插入的数据

    2.判断要插入的队列是否为空队列,若为空,则队头队尾均指向新节点

    3.若不为空,则队尾rear指针指向新节点,然后改新节点为rear

    4.返回队列

queue *in_queue(queue *q,int data)
{
node *p=NULL;
p=(node *)malloc(sizeof(node));
p->data=data;
p->next=NULL;
if(q->rear==NULL)
  q->rear=q->front=p;
else
  {
    q->rear->next=p;
    q->rear=p;
  }
}

4.出队列

队列的出队需要从队头出队

1.定义一个指针p指向队头,若p为空,则打印该队列为空,并返回

2.若p不为空。则队头指向原队头的下一个,并释放原队头

3.若新的队头也指向NULL了,说明队列中所有的元素都出队列了,此时让尾指针也指向NULL

queue *out_queue(queue *q)
{
node *p=NULL;
p=q->front;
if(p==NULL)
 {
  printf("the queue is empty!\n");
  return q;
   }
else
  {
    q->front=q->front->next;
    if(q->front==NULL)
      q->rear=NULL;
free(p); 
  }
     return q;
}


最后贴出完整代码:(还包括测量队列长度和打印队列元素)

#include<stdio.h>
#include<malloc.h>
typedef struct _Node
{
int data;
struct _Node *next;
}node;
typedef struct _Queue
{
node *front;
node *rear;
}queue;
queue *creatqueue()
{
queue *q=(queue *)malloc(sizeof(queue));
q->front=NULL;
q->rear=NULL;
}
queue *in_queue(queue *q,int data)
{
node *p=NULL;
p=(node *)malloc(sizeof(node));
p->data=data;
p->next=NULL;
if(q->rear==NULL)
  q->rear=q->front=p;
else
  {
    q->rear->next=p;
    q->rear=p;
  }
}
queue *out_queue(queue *q)
{
node *p=NULL;
p=q->front;
if(p==NULL)
 {
  printf("the queue is empty!\n");
  return q;
   }
else
  {
    q->front=q->front->next;
    if(q->front==NULL)
      q->rear=NULL;
free(p); 
  }
     return q;
}
int getlength(queue *q)
{
int len=0;
node *p=q->front;
if(p!=NULL)
 len=1;
while(p!=q->rear) 
{
p=p->next;
len++;
}
return len;
}
void printqueue(queue *q)
{
node *p=q->front;
if(p==NULL)
{
printf("the queue is empty!,please quit\n");
return ;
}
printf("the data of the queue is :\n");
while(p!=q->rear)
{
printf("%d\n",p->data);
p=p->next;
}
printf("%d\n",p->data);
}
int main()
{
int len=0;
queue *q=creatqueue();
in_queue(q,1);
in_queue(q,2);
in_queue(q,3);
in_queue(q,4);
in_queue(q,5);
len=getlength(q);
printf("the length of the queue is %d \n",len);
printqueue(q);
out_queue(q);
printqueue(q);
out_queue(q);
printqueue(q);
return 0;
}

原创粉丝点击