用c++來寫鏈表隊列(用到“鏈表”,“隊列”,“封裝”,“繼承”)

本文共分爲3個文件來寫
第一步:給鏈表寫個頭文件,這樣更簡單明瞭
class node
{
public: // 類的 公有封裝
node(); //無參構造函數
node(int); //有參構造函數
friend class Link; //鏈表中的方法
protected: //類的保護封裝
int data;
node* next; //屬性
};
class Link
{
public:
Link(); //構造函數
Link(const Link&); //拷貝構造函數
bool insert(int); //鏈表插入信息
void list(); //鏈表遍歷
bool drop_head(int&); //只刪頭結點(用於隊列的出隊)
protected:
node* front; //頭結點(隊頭)
node* rear; //尾節點(隊尾)
};

/******************************************************************************/
第二步:;鏈表的抒寫:

include

include

include”link”

using namespace std; 以上爲頭文件

node::node():next(NULL) 下列函數對應鏈表頭文件中的函數聲明
{
}
node::node(int d):data(d),next(NULL)
{
}
Link::Link():rear(NULL),front(NULL)
{
}

Link::Link(const Link& s)
{
this->front=NULL;
this->rear=NULL;
node* ph=s.front;
while(ph!=NULL)
{
this->insert(ph->data);
ph=ph->next;
}

}/*
Link::~Link()
{
node* temp=front;
while(this->front!=NULL)
{
this->front=this->front->next;
delete temp;
}

}*/
bool Link::insert(int d)
{
node* pnew=new node(d);
if(pnew==NULL)
return false;
if(front==NULL)
{
front=pnew;
rear=pnew;
}
else
{
rear->next=pnew;
rear=pnew;
}
rear->next=NULL;
return true;
}
void Link::list()
{
node* ph=front;
while(ph!=NULL)
{
cout<data<<” “;
ph=ph->next;
}
cout<

include

include”link” //連接隊列的頭文件

using namespace std;

class Queue:public Link //類的繼承
{
public:
Queue(); //無參構造
Queue(const Queue&); //拷貝構造
bool Isempty(); //判斷隊爲空(由於是鏈表隊列,不考慮隊未滿)
bool Enqueue(int); //進隊
bool Dequeue(int& ); //出隊
void length(); //隊的長度
protected:
int ilen;
}; //下述函數分別對應上述聲明

Queue::Queue():Link(),ilen(0)
{
}
Queue::Queue(const Queue& s):Link(s),ilen(s.ilen)
{

}
void Queue::length()
{
cout<ilen<

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章