温故而知新->数据结构->队列->程序实现1_利用结构体

队列 ~ 程序实现一

本篇博客基于 温故而知新 -> 数据结构 -> 线性表 ->队列 博客中的理论知识,然后利用 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)运行结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值