数据结构之队列的实现【C++】

来源:互联网 发布:交警网络执法直播流程 编辑:程序博客网 时间:2024/04/29 18:04

昨天对链表进行了简单的实现,链表虽然结构简单,但能实现的东西很多,于是乎,今天又用单向链表实现了一个简单版本的队列,所谓队列即FIFO(Fist in Fist out)先进先出的形式(队列队列,跟日常生活中的ATM排队取钱的形式是一样的,在遵守规则的前提之下排在前面的肯定就会先出列取钱,在后进入队列的都会排在队尾,依次类推);
1、首先创建一个Queue.h的头文件

#ifndef __QUEUE_H_#define __QUEUE_H_#include<iostream>#include<string>using namespace std;//template<class T>    struct Info    {        string  val1;        int id;    };    struct Node    {        Info val;        Node * next;        Node(Info x):val(x),next(NULL){};    };class Queue{    private:    Node *head;//队列的头指针    int thesize;//队列的长度public:    Queue();    ~Queue();    void push(Info val);//向队列中压入数据    void pop();//弹出数据    void Print();//将队列中的数据进行打印出来    int Thesize();//返回队列的长度};#endif

这里后期弄成模板,这样数据就可以实现存储各种类型的数据。

2、然后建立一个Queue.cpp的文件,是对Queue.h中类的具体实现,代码如下所示:

#include"Queue.h"Queue::Queue(){    head = NULL;    thesize = 0;}Queue::~Queue(){//  while(thesize!=0)    //  pop();}void Queue::push(Info val){    Node* temp = head;    Node* node = new Node(val);    if(thesize == 0)    {        node->next = temp;        head = node;        thesize++;        return;    }    while(temp->next!=NULL)        temp = temp->next;    if(temp->next == NULL)    {        node->next = temp->next;        temp->next = node;        thesize++;        return;    }}//打印队列void Queue::Print(){    Node* temp = head;    if(temp == NULL)        cout<<"Error:Print failed!"<<endl;    while(temp!=NULL)    {        cout<<temp->val.val1<<"<***>"<<temp->val.id<<endl;        temp = temp->next;    }}//弹出队列void Queue::pop(){    Node* temp = head;    head = temp->next;    thesize--;}//返回队列的长度int Queue::Thesize(){    return thesize;}

通过以上的简单代码的实现,队列基本的压入队列与弹出队列的操作已经有了,还有最基本的打印功能,后期深入再加新的方法。使得其更加全面与完善。

3、建立test.cpp进行测试

#include"Queue.h"int main(int argc,char** argv){    system("color 3F");    Queue temp;    Info val1,val2,val3;    val1.id = 1;val1.val1 = "Wang";val2.id = 2;val2.val1 = "chao";val3.id = 3;val3.val1 = "long";    temp.push(val1);    temp.push(val2);    temp.push(val3);    temp.Print();    cout<<"*****************pop******************"<<endl;    temp.pop();    temp.Print();    cout<<"*****************pushagain***************"<<endl;    temp.push(val1);    temp.Print();    system("pause");    return 0;}

4、总结与结果展示
总结:通过这段时间的学习,让我深知数据结构的重要性,这虽说是基础,但确是万丈高楼的基石,这些必须学好,路还很长,一天进步一点点。白天看机器学习和深度学习的论文,晚上的时间就努力提升自己的coding能力,希望明年的三月份庆幸自己今天的坚持,加油!
这里写图片描述

原创粉丝点击