C语言实现链队列代码

时间:2022-11-02 15:22:22

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#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;
}

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

原文链接:https://blog.csdn.net/u010889616/article/details/47284375