C++建立队列_利用链表

// c++ 实现链表队列

// .h 文件

// 文件名: Queue.h

//-------------------------------------------------
#pragma once

//-------------------------------------------------
#include <iostream>
using namespace std;
//-------------------------------------------------
typedef int dataType;
//------------------------
// 节点类
// 结构名称 Node 
// 参数说明data 为关键字
//         next 为指向下一个节点的指针
struct Node
{
	dataType data;
	Node * next;
};

//-------------------------------------------------
// 队列类,
// 类名 Queue  , 建立链表队列
class Queue
{
public:
	Queue(void);
	~Queue(void);

	void push(dataType  );
	void pop();
	dataType front(); // 获取头元素
	bool IsEmpty(); // 

private:
	Node * head ;    // 头指针
	Node * tail;      // 尾指针

};

//-------------------------------------------------


// .cpp 文件

// 文件名Queue.cpp

//-------------------------------------------------
#include "Queue.h"
//-------------------------------------------------
Queue::Queue(void)
{
	head = NULL;
	tail = NULL; // the queue is empty when head ==NULL  tail == NULL
}
//-------------------------------------------------
Queue::~Queue(void)
{
	Node * ptr = NULL;
	while (head != NULL )
	{
		ptr = head;
		head = head->next;
		delete ptr ;
	}
}
//-------------------------------------------------
void Queue::push(dataType value  )
{
	Node * ptr = new Node ;
	ptr->data = value;
	ptr->next = NULL;

	if (tail != NULL )
	{
		tail->next = ptr;
	}else {
		head = ptr ;
	}

	tail = ptr ;

}
//-------------------------------------------------
void Queue::pop()
{
	Node *ptr = head ;
	head = head->next;
	delete ptr ;
	ptr = NULL;

	if (head == NULL )
		tail = NULL ;
}
//-------------------------------------------------
dataType Queue::front() // 获取头元素  ,当队列为空时,返回值为0
{
	if (this->IsEmpty() == true )
	{
		cout << "the Queue is empty!!" ;
		return 0;
	}
	return head->data;
}
//-------------------------------------------------
bool Queue::IsEmpty()
{
	return head==NULL && tail == NULL;

}
//-------------------------------------------------


// 主函数

// 文件名:main.cpp 

//-------------------------------------------------
// 2014--03--23
// C++ 实现链表队列
//-------------------------------------------------
#include "Queue.h"

//-------------------------------------------------
// 编写主函数进行测试
int main()
{
	Queue qu;
	qu.push(324);
	qu.push(3224);
	qu.push(32324);
	qu.push(3214);
	qu.push(322354);

	cout << qu.front() << endl;

	qu.pop();cout << qu.front() << endl;
	qu.pop();cout << qu.front() << endl;
	qu.pop();cout << qu.front() << endl;
	qu.pop();cout << qu.front() << endl;
	qu.pop();cout << qu.front() << endl;

	cout << qu.IsEmpty() << endl;

	return 0;
}
//-------------------------------------------------






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值