C语言实现链队列代码

发布时间:2020-10-01 12:25:55 作者:dmfrm
来源:脚本之家 阅读:140

本文实例为大家分享了C语言实现链队列的具体代码,供大家参考,具体内容如下

#include <stdio.h>

/* 队列的结构体 */
typedef int DataType;
#define NODE_LEN sizeof(NODE) 

/* 队列的节点 */
typedef struct stNode
{
  DataType data;
  struct stNode* next;
}NODE;

/* 队列 */
typedef struct stQueue
{
  NODE* head; //队列的头
  NODE* tail; //队列的尾
}QUEUE;

/* 初始化队列,不带头结点*/
int initQueue(QUEUE* INQueue)
{

  INQueue->head = NULL;
  INQueue->tail = NULL;

  return 0;
}

/* 从队尾插入一个元素 */
int enQueue(QUEUE* InQueue,DataType InData)
{
  NODE* pNewNode = (NODE*)malloc(NODE_LEN);
  if (pNewNode == NULL)
  {
    return -1;
  }

  pNewNode->data = InData;
  pNewNode->next = NULL;

  /* 判断,现在队列里面有没有节点 */
  if (InQueue->head == NULL)
  {
    InQueue->head = pNewNode;
    InQueue->tail = pNewNode;
  }
  else
  {
    InQueue->tail->next = pNewNode;
    InQueue->tail = pNewNode;
  }

  return 0;
}

/* 遍历该队列 */
int visitQueue(QUEUE InQueue)
{
  QUEUE* pstTemp = &InQueue;

  /* 判断队列是否为空队列 */
  if (pstTemp->head == NULL)
  {
    printf("visitQueue: this queue is empty\n");
    return -1;
  }

  /* 遍历该队列中的所有元素 */
  while (pstTemp->head->next != NULL)
  {
    printf("%d ", pstTemp->head->data);
    pstTemp->head = pstTemp->head->next;
  }
  printf("%d \n", pstTemp->head->data);

  return 0;
}

/* 出队列 */
int delQueue(QUEUE* InQueue,DataType* OutData)
{
  if (InQueue->head == NULL)
  {
    printf("delQueue: this queue is empty\n");
    return -1;
  }

  *OutData = InQueue->head->data;

  NODE* pstTemp = InQueue->head;
  InQueue->head = InQueue->head->next;

  delete pstTemp;
  return 0;
}

/* 判断队列是否是空队列 */
int isEmptyQueue(QUEUE InQueue)
{
  if (InQueue.head == NULL)
  {
    return 0; //是空队列
  }
  return 1; //不是空队列
}

int main()
{
  /* 创建一个队列 */
  QUEUE queue;
  DataType data;

  initQueue(&queue);

  /* 入队列 */
  enQueue(&queue, 12);
  enQueue(&queue, 11);
  enQueue(&queue, 2);
  visitQueue(queue);

  /* 出队列 */
  delQueue(&queue, &data);
  visitQueue(queue);
  printf("data = %d\n", data);

  visitQueue(queue);

  if (0 == isEmptyQueue(queue))
  {
    printf("This is empty queue\n");
  }
  else
  {
    printf("This is not empty queue\n");
  }
  return 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. c语言颜色代码如何实现
  2. c语言实现星号爱心的代码

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c语言 链队列

上一篇:Angular2.0实现modal对话框的方法示例

下一篇:python pip安装包出现:Failed building wheel for xxx错误的解决

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》