面向?qū)ο笊蠙C考試題—關(guān)于隊列

字號:

請實現(xiàn)一個隊列,既可以存放整數(shù),又可以存放字符串。簡單的說,隊列是一種數(shù)據(jù)結(jié)構(gòu),按照先進先出的順序管理進、出隊列的元素。本題要求完成:
    (1) 實現(xiàn)描述隊列的類Queue,其中定義了隊列的大小Size(即隊列中可以存放的元素個數(shù)),并包括進隊列函數(shù)Add,出隊列函數(shù)Delete、顯示隊列頭部元素的函數(shù)Head和顯示隊列尾部元素的函數(shù)Tail.
    (2) 定義基類Element,至少包含純虛函數(shù)ShowMe.
    (3) 從基類Element中派生整數(shù)類MyInteger和字符串類MyString, 具體實現(xiàn)上述純虛函數(shù)ShowMe,顯示該元素的類型和相應(yīng)的值。
    (4) 重載輸入“>>”*作符,使得可以通過cin直接讀入上述整數(shù)類和字符串類的對象值。
    (5) 編寫main函數(shù),測試上述所要求的各種功能,即可以根據(jù)菜單命令增加隊列元素、刪除隊列元素、顯示隊列頭部元素和隊列尾部元素,其中的元素可以是整數(shù)和/或字符串。
    提示:
    虛擬基類Element的定義至少包括以下純虛函數(shù)ShowMe.
    class Element
    {
     // ……
    public:
     virtual void ShowMe () = 0;
     // ……
    };
    */
    #include "stdafx.h"
    #include "iostream.h"
    #include "string.h"
    const max=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);
     int Get() {return a;};
     void ShowMe()
    };
    istream &operator>>(istream &is, MyInteger &MyI)
    {
     cout<<" 請輸入整數(shù):";
     is>>MyI.a;
     return is; }
    class MyString:public Element
    { char s[100];
    public:
     friend istream &operator>>(istream &is, MyString &MyS);
     void ShowMe()
    };
    istream &operator>>(istream &is, MyString &MyS)
    {
     cout<<" 請輸入字符串:";
     is>>MyS.s;
     return is;
    }
    class Queue
    { int size;
     Element *Elm[max];
     MyInteger MyI[max];
     MyString MyS[max];
    public:
     Queue(){
     for (int i=0; i     Elm[i]=NULL;
     size=-1;
     }
     void add(MyInteger &My)
     {
     if (full()) cout<<"隊列已滿"<     else {
     MyI[++size]=My;
     Elm[size]=new MyInteger;
     Elm[size]=&MyI[size];
     }
     }
     void add(MyString &My)
     {
     if (full()) cout<<"隊列已滿"<     else {
     MyS[++size]=My;
     Elm[size]=new MyString;
     Elm[size]=&MyS[size];
     }
     }
     void tail()
     { if(empty()) cout<<"隊列為空"<     else{
     cout<<" 隊列的尾元素為";
     Elm[size]->ShowMe();
     }
     }
     void head()
     {
     if(empty()) cout<<"隊列為空"<     else{
     cout<<" 隊列的頭元素為";
     Elm[0]->ShowMe();
     }
     }
     void del()
     {
     if(empty()) cout<<"隊列為空"<     else{
     cout<<" 出隊列的元素為";
     Elm[size--]->ShowMe();
     }
     }
     bool empty()
     {
     return (bool)(size==-1);
     }
     bool full()
     {
     return (bool)(size==max-1);
     }
    };
    void main()
    { MyInteger my1;
     MyString my2;
     Queue queue;
     int s=1;
     while(s)
     {
     cout<<"Please select 1-6 "<     cout<<" 1: 整數(shù)進隊列;"<     cout<<" 2: 字符串進隊列;"<     cout<<" 3: 顯示隊列頭元素;"<     cout<<" 4: 顯示隊列尾元素"<     cout<<" 5: 出隊列;"<     cout<<" 6: 退出程序"<     cout<<"--------------------------------------"<     cout<<"請選擇您的*作:";
     cin>>s;