数据结构—链队

链队
以单链表的形式 FIFO 特征
在这里插入图片描述
在这里插入图片描述
代码部分

结点
struct Node
{
ElemType data;
struct Node* next;
};

头指针和尾指针
struct Queue
{
struct Node* phead;
struct Node* ptail;
};

新建Queue.h
typedef int ElemType;//先定义一个元素类型

typedef struct Node//建立结点结构
{
	ElemType data;
	struct Node* next;
}Node;

typedef struct LQueue//建立队列结构
{
	struct Node* phead;
	struct Node* ptail;
}LQue,*pQue;

void init(pQue pqu);//初始化函数

Node* buyNode(ElemType val);//返回生成新结点  data = val  next = NULL 
void enqueue(pQue,Elemtype val);//尾插

int empty(pQue pqu);//0  not NULL  1  NULL
int dequeue(pQue pqu);//头删  返回值  0 出队fail  1  出队  success
int front(pQue pqu0);//获取队头元素
int back(pQue pqu);//获取队尾元素
 
void clear(pQue pqu);//清理数据   结构不销毁
void destroyed(pQue pqu);//销毁所有结构

新建Queue.cpp
#include<stdio.h>
#include<stdlib.h>
#include"Queue.h"

void init (pQue pqu)
{
	if(pqu != NULL)
	{
		Node* pnhead = (Node*)malloc(sizeof(Node));//先生成头结点   堆上开辟
		pnhead->next = NULL;//指针域为空
		pqu->phead = pqu->ptail = pnhead;//头指针和尾指针在同一位置
	}
}

Node* buyNode(ElemType val)
{
	Node* pnewnode = (Node*)malloc(sizeof(Node));
	pnewnode->data = val;
	pnewnode->next = NULL;
	return pnewnode;
}Node;

void enqueue(pQue pqu,ElemType val)
{
	Node* pnewnode = buyNode(val);//新结点生成
	pqu->ptail->next = pnewnode;//尾部的next指向新结点
	pqu->ptail = pnewnode;//尾部指针指向尾部节点
}

int empty(pQue pqu)
{
	return((pqu->phead == pqu->ptail)&&(pqu->phead != NULL));
	if(pqu != NULL)
	{
		return 0;
	}
}

int dequeue(pQue pqu)
{
	if(empty(pqu))
	{
		return 0;
	}
	Node* pdelete = pqu->phead->next;
	pqu->phead->next = pdelete->next;
	if(pqu->phead->next == NULL);
	{
		pqu->ptail = pqu->phead;
	}
	free(pdelete);
	return 1;
}

#include<iostream>
using namespace std;
int front (pQue pqu)
{
	if(empty(pqu))
	{
		throw exception("queue is empty");//代码跳转到调用方
	}
	return pqu->phead->next->data;
}

int back(pQue pqu)
{
	if(empty(pqu))
	{
		return -1;//牺牲一个数据位  -1
	}
	return pqu->ptail->data;
}
void clear(pQue pqu)
{
	Node* pCur = pqu->phead->next;//当前节点为第一个数据节点
	Node* pnext;
	while(pCur != NULL)
	{
		pnext = pCur->next;
		free(pCur);
		pCur = pnext;
	}
	pqu->phead->next = NULL;
}


void destroyed (pQue pqu)
{
	clear(pqu);
	free(pqu->phead);
	pqu->phead = pqu->ptail = NULL;
}


新建main.cpp
#include<stdio.h>
#include"Queue.h"

int main()
{
	LQue que;
	init (&que);
	for(int i = 0;i<5;i++)
	{
		enqueue(&que,i+1);
	}
	printf("front:%d\n",front(&que));
	printf("back:%d\n",back(&que));
	
	dequeue(&que);
	printf("front:%d\n",front(&que));
	printf("back:%d\n",back(&que));

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有头发的小小猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值