1. 程式人生 > >請實現一個佇列,既可以存放整數,又可以存放字串。簡單的說,佇列是一種資料結構,按照先進先出的順序管理進、出佇列的元素

請實現一個佇列,既可以存放整數,又可以存放字串。簡單的說,佇列是一種資料結構,按照先進先出的順序管理進、出佇列的元素

請實現一個佇列,既可以存放整數,又可以存放字串。簡單的說,佇列是一種資料結構,按照先進先出的順序管理進、出佇列的元素。本題要求完成:

  (1) 實現描述佇列的類Queue,其中定義了佇列的大小Size(即佇列中可以存放的元素個數),幷包括進佇列函式Add,出佇列函式Delete、顯示佇列頭部元素的函式Head和顯示佇列尾部元素的函式Tail.

  (2) 定義基類Element,至少包含純虛擬函式ShowMe.

  (3) 從基類Element中派生整數類MyInteger和字串類MyString, 具體實現上述純虛擬函式ShowMe,顯示該元素的型別和相應的值。

  (4) 過載輸入“>>”*作符,使得可以通過cin直接讀入上述整數類和字串類的物件值。

  (5) 編寫main函式,測試上述所要求的各種功能,即可以根據選單命令增加佇列元素、刪除佇列元素、顯示佇列頭部元素和佇列尾部元素,其中的元素可以是整數和/或字串。

  提示:

  虛擬基類Element的定義至少包括以下純虛擬函式ShowMe.

class Element 

 // ……  
public: 
  virtual void ShowMe () = 0; 
 // ……  
}; 
*/ 

#include <iostream> 
#include <cstring> 
using namespace std;
const int MAXN=1000; 
#define NULL 0

class Element 
{ 
public:
	virtual void ShowMe() = 0; 
}; 

class MyInteger:public Element 
{ 
	int a; 
public: 
	//MyInteger() ;
	friend istream &operator>>(istream &is, MyInteger &MyI); 
	void ShowMe()
	{
		cout << "整形" << a << endl;
	}
}; 
istream &operator>>(istream &is, MyInteger &MyI) 
{ 
	cout<<" 請輸入整數:"; 
	is>>MyI.a; 
	return is;
} 

class MyString:public Element 
{ 
	char s[100]; 
public: 
	friend istream &operator>>(istream &is, MyString &MyS); 
	void ShowMe()
	{
		cout << "字串" << s << endl;
	}

}; 
istream &operator>>(istream &is, MyString &MyS) 
{ 
	cout<<" 請輸入字串:"; 
	is>>MyS.s; 
	return is; 
} 
class Queue 
{ 
	int size; 
	Element *Elm[MAXN]; 
	MyInteger MyI[MAXN]; 
	MyString MyS[MAXN]; 
public: 
	Queue()
	{ 
		for(int i=0; i<MAXN; i++) 
			Elm[i]=NULL; 
		size=-1; 
	} 
	void add(MyInteger &My) 
	{ 
		if (full()) cout<<"佇列已滿"<<endl; 
		else { 
			MyI[++size]=My; 
			Elm[size]=new MyInteger; 
			Elm[size]=&MyI[size]; 
		} 
	} 
	void add(MyString &My) 
	{ 
		if (full()) cout<<"佇列已滿"<<endl; 
		else { 
			MyS[++size]=My; 
			Elm[size]=new MyString; 
			Elm[size]=&MyS[size]; 
		} 
	} 

	void tail() 
	{ if(empty()) cout<<"佇列為空"<<endl;  
	else{ 
		cout<<" 佇列的尾元素為"; 
		Elm[size]->ShowMe(); 
	} 
	} 
	void head() 
	{  
		if(empty()) cout<<"佇列為空"<<endl; 
		else{ 
			cout<<" 佇列的頭元素為"; 
			Elm[0]->ShowMe(); 
		} 
	} 
	void del() 
	{ 
		if(empty()) cout<<"佇列為空"<<endl;  
		else{ 
			cout<<" 出佇列的元素為"; 
			Elm[size--]->ShowMe();  
		} 
	} 
	bool empty() 

	{ 
		return (bool)(size==-1);  
	} 
	bool full() 
	{ 
		return (bool)(size==MAXN-1); 
	} 
}; 
int main() 
{ 
	MyInteger my1; 
	MyString my2; 
	Queue queue; 
	int s=1; 
	while(s) 
	{ 
		cout<<"Please select 1-6 "<<endl; 
		cout<<" 1: 整數進佇列;"<<endl; 
		cout<<" 2: 字串進佇列;"<<endl; 
		cout<<" 3: 顯示佇列頭元素;"<<endl; 
		cout<<" 4: 顯示佇列尾元素"<<endl; 
		cout<<" 5: 出佇列;"<<endl; 
		cout<<" 6: 退出程式"<<endl; 
		cout<<"--------------------------------------"<<endl; 
		cout<<"請選擇您的*作:"; 
		cin>>s; 
		switch(s) 
		{ 
		case 1: cin>>my1; queue.add(my1); break; 
		case 2: cin>>my2; queue.add(my2); break; 
		case 3: queue.head(); break; 
		case 4: queue.tail(); break; 
		case 5: queue.del(); break; 
		default: s=0; break; 
		} 
} 
}