链式队列的实现

#include <iostream>

using namespace std;

struct QueueNode{

int data;

QueueNode* next;

};

struct LinkQueue{

QueueNode* top;

QueueNode* rear;

};

void InitQueue(LinkQueue*& Q) {

Q = new LinkQueue;

Q->top = Q->rear = new QueueNode; //设头结点便于操作

Q->top->next = 0;

}

int Push(LinkQueue*& Q, int x) {

QueueNode* p = new QueueNode;

if (p == 0) return 0;

p->data = x;

p->next = 0;

Q->rear->next = p;

Q->rear = p;

return 1;

}

int Pop(LinkQueue*& Q) {

if (Q->rear == Q->top) return 0;

QueueNode* p = Q->top->next;

if (p->next == 0) {

Q->top->next = 0;

Q->rear = Q->top;

}

else {

Q->top->next = p->next;

}

delete p;

return 1;

}

int GetTop(LinkQueue* Q,int &x) { //得到队头元素

if (Q->rear == Q->top) return 0;

x = Q->top->next->data;

return 1;

}

bool IsEmpty(LinkQueue* Q) { //判断列表是否为空

if (Q->rear == Q->top)

return true;

return false;

}

void Print(LinkQueue* Q) { //打印队列

QueueNode* p = Q->top->next;

while (p){

if (p != Q->top->next) cout << ' ';

cout << p->data;

p = p->next;

}

cout << endl;

}

int main() {

LinkQueue* Q;

InitQueue(Q);

Push(Q, 1);

Push(Q, 2);

Push(Q, 3);

Push(Q, 4);

Push(Q, 5);

Print(Q);

cout << IsEmpty(Q) << endl;

int x;

GetTop(Q, x);

cout << x << endl;

Pop(Q);

Print(Q);

Pop(Q);

Pop(Q);

Pop(Q);

Pop(Q);

Pop(Q);

cout << IsEmpty(Q);

return 0;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,054评论 0 2
  • 栈和队列也是线性表,栈和队列的进本操作是线性表操作的子集,它们是操作受限的线性表 栈: 限定仅在表尾进行插入或者删...
    一川烟草i蓑衣阅读 170评论 0 0
  • 1.把二元查找树转变成排序的双向链表 题目: 输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。 要求不...
    曲终人散Li阅读 3,371评论 0 19
  • #include using namespace std; struct LinkNode { int data;...
    冰糖葫芦梧加皮阅读 193评论 0 0
  • 睡吧人啊不然你能睁着眼吃掉这些病痛能活下来已经不错了别再和自己过不去了让呼吸沉入其中那是多么让人难受的事情其实病的...
    语蔓阅读 132评论 1 5