链队列出入队列c语言程序,链队列及(C++)实现详解

围绕链表构建的动态队列比静态队列更直观。一个动态队列将作为一个空链表开始。在第一次入队操作中,增加了一个结点,并且 front 和 rear 指针均指向它。随着每个新项目被添加到队列中,新的结点被添加到链表的后面,并且 rear 指针被更新以指向新结点。

当有项目要出队时,使 front 指向链表中的下一个结点,然后删除先前 front 所指向的结点。 图 1 显示了一个动态队列的结构。

8cd39d788f014285a8f2dac200c747a7.gif

图 1 实现为链表的动态队列

动态整数队列类 DynIntQueue 的代码清单如下所示:

//DynIntQueue.h

class DynIntQueue

{

struct QueueNode

{

int value;

QueueNode *next;

QueueNode(int value1, QueueNode *next1 = nullptr)

{

value = value1;

next = next1;

}

};

// These track the front and rear of the queue

QueueNode *front;

QueueNode *rear;

public:

// Constructor and Destructor

DynIntQueue();

~DynIntQueue();

// Member functions

void enqueue(int);

void dequeue(int &);

bool isEmpty() const;

void clear();

};

//DynIntQueue.cpp

#include

#include "DynIntQueue.h"

#include

using namespace std;

DynIntQueue::DynIntQueue()

{

front = nullptr;

rear = nullptr;

}

DynIntQueue::~DynIntQueue()

{

QueueNode * garbage = front;

while (garbage != nullptr)

{

front = front->next;

garbage->next = nullptr;

delete garbage;

garbage = front;

}

}

void DynIntQueue::enqueue(int num)

{

if (isEmpty())

{

front = new QueueNode(num);

rear = front;

}

else

{

rear->next = new QueueNode(num);

rear = rear->next;

}

}

void DynIntQueue::dequeue(int &num)

{

QueueNode *temp = nullptr;

if (isEmpty())

{

cout << "The queue is empty.\n";

exit(1);

}

else

{

num = front->value;

temp = front;

front = front->next;

delete temp;

}

}

bool DynIntQueue::isEmpty() const

{

if (front == nullptr)

return true;

else

return false;

}

void DynIntQueue::clear()

{

int value; // Dummy variable for dequeue

while (!isEmpty())

dequeue(value);

}

下面的程序是一个驱动模块程序,它演示了 DynIntQueue 类的使用:

// This program demonstrates the DynIntQueue class

#include

#include "DynIntQueue.h"

using namespace std;

int main()

{

DynIntQueue iQueue;

cout << "Enqueuing 5 items...\n";

// Enqueue 5 items

for (int k = 1; k <= 5; k++)

iQueue.enqueue(k*k);

// Deqeue and retrieve all items in the queue

cout << "The values in the queue were: \n";

while (!iQueue.isEmpty())

{

int value;

iQueue.dequeue(value);

cout << value << " ";

}

return 0;

}

程序输出结果:

Enqueuing 5 items...

The values in the queue were:

1 4 9 16 25

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值