昨天對鏈表進行了簡單的實現,鏈表雖然結構簡單,但能實現的東西很多,於是乎,今天又用單向鏈表實現了一個簡單版本的隊列,所謂隊列即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能力,希望明年的三月份慶幸自己今天的堅持,加油!