队列 ~ 程序实现一
本篇博客基于 温故而知新 -> 数据结构 -> 线性表 ->队列 博客中的理论知识,然后利用 C
中的 结构体 对数据结构中的 队列 进行代码实现!
其中涉及了队列的 增(入队)删(出队)查(队头与队尾元素)改(没写(~ ̄▽ ̄)~),判空,打印等操作!并附带了实例以及对应的运行结果!
注意:本篇博客中 队列 的程序实现借鉴了 利用结构体实现单向链表 的程序!
具体内容如下
(1)newQueue.h
#ifndef __NEWQUEUE_H_
#define __NEWQUEUE_H_
#include<stdio.h>
#include<stdlib.h>
//队列:带有尾指针的单链表
typedef int QDataType;
typedef struct QNode
{
QDataType _data;
struct QNode* _next;
}QNode;
typedef struct Queue
{
//头尾指针
struct QNode * _head;
struct QNode * _tail;
int _size;
}Queue;
#endif
(2)main.c
#include"newQueue.h"
void initQueue(Queue * q)
{
if (q == NULL)
return;
q->_head = NULL;
q->_tail = NULL;
q->_size = 0;
}
struct QNode* creatNode(QDataType val)
{
struct QNode * newNode = (struct QNode*)malloc(sizeof(struct QNode));
newNode->_data = val;
newNode->_next = NULL;
return newNode;
}
void queuePush(Queue * q, QDataType val)
{
if (q == NULL)
return;
//尾插
struct QNode*node = creatNode(val);
//第一个节点
if (q->_head == NULL)
q->_head = q->_tail = node;
else
{
q->_tail->_next = node;
q->_tail = node;
}
++q->_size;
}
void queuePop(Queue * q)
{
//头删
if (q == NULL || q->_head == NULL)
return;
struct QNode * next = q->_head->_next;
free(q->_head);
q->_head = next;//q的头指向next
--q->_size;
if (q->_head == NULL)
q->_tail = NULL;//只有一个节点头删后,空队列
}
void queuePrint(Queue *q)
{
if (q == NULL || q->_head == NULL)
return;
QNode *cur = q->_head;
printf("队列元素数据:");
while (cur != NULL)
{
printf("%d ", cur->_data);
cur = cur->_next;
}printf("\n");
}
QDataType queueFront(Queue *q)
{
return q->_head->_data;
}
QDataType queueBack(Queue *q)
{
return q->_tail->_data;
}
int queueEmpty(Queue *q)
{
return q->_head == NULL;
}
int queueSize(Queue *q)
{
if (q == NULL)
return 0;
return q->_size;
}
void test()
{
struct Queue q;
initQueue(&q);
queuePush(&q, 1);
queuePush(&q, 2);
queuePush(&q, 3);
queuePush(&q, 4);
queuePrint(&q);
printf("\n");
printf("同时打印与取出队列元素:");
while (!queueEmpty(&q))
{
printf("%d ", queueFront(&q));
queuePop(&q);
}
printf("\n\n");
printf("队列元素数据:");
queuePrint(&q);
printf("\n");
/*queuePop(&q);
queuePop(&q);
queuePop(&q);*/
}
int main()
{
test();
system("pause");
return 0;
}
(3)运行结果