博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
队列实现 (双向循环链表 C++)
阅读量:4310 次
发布时间:2019-06-06

本文共 2224 字,大约阅读时间需要 7 分钟。

队列是非常easy的。可是用数组实现可能更好点。

(事实上我认为数组在多个队列的时候更难)

然后我是第一次写双向循环链表。指向太乱了。

我这里是依照自己的想法。建立了一个头节点,一个尾节点,然后依照队列顺序正向插入到两个节点之间。输出和弹出队列的时候从后面操作。

以下上代码:

////  main.cpp//  queue////  Created by Alps on 14-7-28.//  Copyright (c) 2014年 chen. All rights reserved.//#include 
#define ElementType intusing namespace std;struct Node;typedef Node* PtrToNode;typedef PtrToNode Queue;struct Node{ ElementType X; PtrToNode Pre; PtrToNode Next;};Queue createQueue(void){ Queue Q; Queue Q2; Q2 = (Queue)malloc(sizeof(Node)); Q = (Queue)malloc(sizeof(Node)); Q->X = 0; Q->Next = Q2; Q->Pre = Q2; Q2->Next = Q; Q2->Pre = Q; return Q;}int isEmpty(Queue Q){ return Q->Next->Next == Q;}void intoQueue(Queue Q, ElementType element){ Queue tmp; Queue tmp1; tmp1 = (Queue)malloc(sizeof(Node));// Queue switchTmp; tmp = (Queue)malloc(sizeof(Node)); tmp->X = element; tmp->Next = Q->Next; Q->Next->Pre = tmp; Q->Next = tmp; tmp->Pre = Q;}void outQueue(Queue Q){ Queue tmp; tmp = Q->Pre->Pre; Q->Pre->Pre = tmp->Pre; tmp->Pre->Next = Q->Pre; free(tmp);}ElementType headQueue(Queue Q){ if (Q == NULL) { printf("please create queue first!\n"); return 0; } if (!isEmpty(Q)) { return Q->Pre->Pre->X; }else{ printf("The queue is empty!\n"); return 0; }}int makeEmpty(Queue Q){ if (Q == NULL) { printf("please create queue first!\n"); return -1; } while (!isEmpty(Q)) { outQueue(Q); } return 0;}void Print(Queue Q){ if (!isEmpty(Q)) { Queue tmp = Q->Pre->Pre; while (tmp != Q) { printf("%d ",tmp->X); tmp = tmp->Pre; } printf("\n"); }}int main(int argc, const char * argv[]){ Queue Q = createQueue(); if (isEmpty(Q)) { printf("The queue is empty !\n"); }else{ printf("The queue is not empty!\n"); } intoQueue(Q, 2); intoQueue(Q, 4); intoQueue(Q, 6); Print(Q); outQueue(Q); Print(Q); makeEmpty(Q); Print(Q);// printf("%d\n",headQueue(Q)); return 0;}
这个代码比較乱 = = ,多包涵了,我以后想想简单点的方法实现。事实上单链表也能够。可是那样操作就不是O(1)了,所以才用双链表。

转载于:https://www.cnblogs.com/lxjshuju/p/6807873.html

你可能感兴趣的文章
cocos2d lua的cclog 在logcat中显示
查看>>
雅礼学习10.4
查看>>
Dota2 荒神罪 破解
查看>>
TP控制器的操作
查看>>
Installing Oracle Database 12c Release 2(12.2) RAC on RHEL7.3 in Silent Mode
查看>>
使用Metasploit进行端口扫描
查看>>
[LeetCode] 258. Add Digits
查看>>
python3.5+ asyncio await异步详解
查看>>
android手机获取手机号
查看>>
Android和WCF通信 - 大数据压缩后传输
查看>>
TC中HTB的使用备注
查看>>
深入学习Redis(1):Redis内存模型
查看>>
当Eclipse爱上SVN
查看>>
hdu 4586 Play the Dice (概率+等比数列)
查看>>
阿里云api调用做简单的cmdb
查看>>
软考笔记
查看>>
ORACLE 日期函数
查看>>
【Java基础总结】数据库编程
查看>>
SVN commit:remains in tree-conflict错误的解决办法
查看>>
PHP不使用内置函数intval(),实现字符串转整数
查看>>