顺式队列的实现和链式队列的实现
顺式队列,用数组保存队列中的各个元素的值,front和rear分别指向队列中的第一个和最后一个元素。
代码如下:#include <stdio.h>
#include <malloc.h>
#define max_size 50
typedef struct Queue {
int arr[max_size];
int front;
int rear;
}queue;
queue *create()
{
queue *q = (queue *)malloc(sizeof(queue));
q->front = 0;
q->rear = 0;
return q;
}
void enqueue(queue *q, int val)
{
q->arr[q->rear] = val;
++ q->rear;
}
void dequeue(queue *q, int *val)
{
*val = q->arr[q->front];
++ q->front;
}
void destroy(queue *q)
{
free(q);
}
int main()
{
queue *q;
q = create();
int a = 1, b = 2;
int c;
enqueue(q, a);
enqueue(q, b);
while (q->rear != q->front) {
dequeue(q, &c);
printf("%d\n", c);
}
destroy(q);
return 0;
}
链式队列的实现,链表存储队列中的元素,队列必有两个指针front和rear分别指向队列中的第一个元素和最后一个元素,入队列和出队列是队列中的基本操作,入队列对应是链表的插入操作,在队列的尾部入队列,rear->next指向新插入入队列的元素;出队列对应的是链表的删除操作,从队列的头部出队列,删除链表中某一个元素要找到该元素的前一个元素,且是从队列头删除元素,如果不加头结点,删除头指针时需要特殊处理,因此添加头结点达到统一处理链表中元素的目的。
出队列时,需要特别注意。一般出队列,只需要修改头结点中的指针,但当队列中最后一个元素被删后,队列尾指针也丢失,因此需要对队尾指针重新赋值,指向头结点,且判断队列是否为空的条件是,队列的头指针和尾指针是否指向同一个元素。
代码:
#include <stdio.h>
#include <malloc.h>
typedef struct LNode {
int val;
struct LNode *next;
}node;
typedef struct Queue {
node *front;
node *rear;
}queue;
queue *create()
{
queue *q = (queue *)malloc(sizeof(queue));
node *head = (node *)malloc(sizeof(node));
head->next = NULL;
q->front = head;
q->rear = head;
return q;
}
void enqueue(queue *q, int value)
{
node *p = (node *)malloc(sizeof(node));
p->val = value;
p->next = NULL;
q->rear->next = p;
q->rear = p;
}
void dequeue(queue *q, int *value)
{
if (q->front == q->rear)
return;
node *tmp = q->front->next;
*value = q->front->next->val;
q->front->next = tmp->next;
if (q->rear == tmp)
q->rear = q->front;
free(tmp);
}
void destroy(queue *q)
{
free(q);
}
int main()
{
queue *q;
q = create();
int a = 1, b = 2;
int c;
enqueue(q, a);
enqueue(q, b);
while (q->rear != q->front) {
dequeue(q, &c);
printf("%d\n", c);
}
destroy(q);
return 0;
}
链式栈和链式队列都是新插入的节点的next指向top或rear节点,这样就可以把节点都连接起来。