数据结构---栈和队列之链队(C语言)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lu_LLLR/article/details/79960527

链队就是采用链式存储结构存储队列,这里采用单链表来实现。链队的特点是不存在队列满上溢的情况(这里也不太严格,内存满了就上溢了,但是一般内存是不会满的)。
----------------------------------------------------------------------------------------------------------------------------------

完整代码如下

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
/***************队结点定义*************/
typedef struct QNode
{
 int data;   //数据域
 struct QNode *next;
}LQNode;
/***************链队类型定义***********/
typedef struct
{
 LQNode *front;   //队首指针
 LQNode *rear;    //队尾指针
}LiQueue;
LiQueue *lqu;
/****************初始化链队**************/
void initQueue()
{
 lqu = (LiQueue*)malloc(sizeof(LiQueue));
 lqu->front = lqu->rear = NULL;
}
/***************判断队空*****************/
int isQueueEmpty()
{
 if (lqu->front == NULL || lqu->rear == NULL)
  printf("队空");
 else
  printf("队不空");
}

/******************入队*******************/
int count = 0;   //输入了多少数据计数
void enQueue()
{
 LQNode *p; 
 printf("请输入数据,按回车键结束!\n");
 printf("入队数据顺序为:\n");
 while (1)
 {
  p = (LQNode*)malloc(sizeof(LQNode));
  scanf_s("%d", &p->data);
  count++;
  
  p->next = NULL;
  if (lqu->rear == NULL)
   lqu->front = lqu->rear = p;   //若队列为空,则新节点是队首结点也是队尾结点
  else
  {
   lqu->rear->next = p;   //将新结点链接到队尾,rear指向它
   lqu->rear = p;
  }
  char c = getchar();
  if (c == '\n')
   break;
 }
 return lqu;
}
/********************出队*******************/
int deQueue()
{
 LQNode *p;
 printf("\n出队数据顺序为:");
 for (int i = 0; i < count; i++)
 {
  if (lqu->rear == NULL)   //队空不能出列
   return 0;
  else
   p = lqu->front;
  if (lqu->front == lqu->rear)   //队列中只有一个结点时的出队操作需要特殊处理
  {
   lqu->front = lqu->rear = NULL;
   printf("%d  ", p->data);
   free(p);
  }   
  else
  {
   lqu->front = lqu->front->next;
   printf("%d  ", p->data);
   free(p);
  }  
 } 
 return 1;
}
int main()
{
 initQueue();
 isQueueEmpty();
 enQueue();
 deQueue();
 system("pause");
}
 
 
结果图:

猜你喜欢

转载自blog.csdn.net/lu_LLLR/article/details/79960527