双链表详解

双链表又称队列,这是一种常见且有用的数据结构,例如服务行业管理中使用这种数据结构的程序数不胜数,当然游戏方面这种结构也大有用武之地。

队列数据结构可视图形如下:

(a)视图为当前队列情况,(b)视图为删除一个节点后的情况,由图可知队列是一种先进先出的结构,与栈结构相反。

队列模板如下:

/* queue.h -- 队列接口 */

#ifndef _QUEUE_H
#define _QUEUE_H
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

/* 队列最大数 */
#define MAXQUEUE 10


/* custom module 自定义模块 */
typedef struct item {
	char key;
} Item;

/* 可以访问到下一个节点 */
typedef struct node {
	Item item;
	struct node * next;
} Node;

/* 队列定义 */
typedef struct queue {
	Node * front; // 指向队列的首部
	Node * rear;  // 指向队列的尾部
	int items;
} Queue;

void InitQueue(Queue * queue);
bool QueueIsFull(Queue * queue);
bool QueueIsEmpty(Queue * queue);
bool EnQueue(Item item, Queue * pq);
bool DeQueue(Item * item, Queue * pq);
void EmptyTheQueue(Queue * pq);
static void CopyToNode(Item item, Node * pn);
static void CopyToItem(Item * pi, Node * pn);

#endif 
#include "queue.h"

void InitQueue(Queue * pq)
{
	pq->front = pq->rear = NULL;
	pq->items = 0;
}

bool QueueIsFull(Queue * queue)
{
	return queue->items == MAXQUEUE;
}

bool QueueIsEmpty(Queue * queue)
{
	return queue->items == 0;
}

static void CopyToNode(Item item, Node * pn)
{
	pn->item = item;
}

bool EnQueue(Item item, Queue * pq)
{
	Node * pnew;

	if (QueueIsFull(pq))				 // 检查项目是否满载
		return false;	 
	pnew = (Node *)malloc(sizeof(Node)); // 申请堆空间
	if (pnew == NULL)					 // 如果申请失败
	{
		fprintf(stderr, "Unable to allocate memory!\n");
		exit(1);			
	}
	CopyToNode(item, pnew);		// 复制节点内容
	pnew->next = NULL;			// 节点指向为空
	if (QueueIsEmpty(pq))		// 检查项目是否为空
		pq->front = pnew;		// 首指针指向首部节点
	else
		pq->rear->next = pnew;  // 链接到队列尾部
	pq->rear = pnew;			// 尾指针指向新节点
	pq->items++;				// 项目个数加1 
	return true;
}

static void CopyToItem(Item * pi, Node * pn)
{
	*pi = pn->item;
}

bool DeQueue(Item * item, Queue * pq)
{
	Node * pt;					 // 临时节点保存当前首部

	if (QueueIsEmpty(pq))
		return false;
	CopyToItem(item, pq->front);
	pt = pq->front;
	pq->front = pq->front->next; // 指向首部的下一个节点
	free(pt);					 // 释放当前首部节点
	pq->items--; 
	if (pq->items == 0)			 // 项目为空
		pq->rear = NULL;		 // 设置尾部节点指向为空
	return true;
}

void EmptyTheQueue(Queue * pq)
{
	Item dummy;
	while (!QueueIsEmpty(pq))
		DeQueue(&dummy,pq);
}
#include "queue.h"

int main()
{
	Queue key;
	Item temp;
	char ch;

	InitQueue(&key);

	while ((ch = getch()) != 'q')
	{
		switch (ch)
		{
		case 'd':
			if (DeQueue(&temp, &key))
				printf("Del is Ok.\n");
			break;
		}
		EnQueue(temp, &key);
		printf("now %d items\n", key.items);
	}
	EmptyTheQueue(&key);
	return 0;
}

这个源代码思路很简单,Item大家可以自行定义来实现您需要的功能。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值