栈 和 队列

class Q{//队列类
  private:
    int head;
    int tail;
    int length;
    bool flag;
    int *p;
  public:
    Q(int c,int a = 0,int b = 0,int d = 0){//构造函数
      head = a;
      tail = b;
      length = c;
      flag = d;
      p = new int[c];
      for(int i = 0;i < length;i++){
        p[i] = 0;
      }
    }
    void Qprint(){
      for(int j = 0;j <length;j++){
        cout<<p[j]<<endl;
      }
    }
    void ENQ(int x){//入队列
      if(flag == 1){
        if(tail == length){
          cout<<tail;
          tail = 0;
          if(tail == head){
            cout<<"上溢出!"<<head<<endl;
            tail = length;
          }else{
            p[length-1] = x;
          }
        }else{
          tail = tail+1;
          if(tail == head){
            cout<<"上溢出!"<<endl;
            tail = tail-1;
          }else{
            p[tail-1] = x;
          }
        }
      }else{
        tail = tail+1;
        p[head] = x;
        flag = 1;
      }
    }
    int DEQ(){//出队列
      if(flag == 1){
        if(head != tail){
          if(head < length-1){
            head++;
            return p[head-1];
          }else{
            head = 0;
            return p[length-1];
          }
        }else{
          return p[head];
          flag = 0;
        }
      }else{
        cout<<"下溢出!"<<endl;
        return -1;
      }
    }
};
class S{//栈类
  private:
    int head;
    int tail;
    int length;
    bool flag;
    int *p;
  public:
    S(int c,int a = 0,int b = 0,int d = 0){//构造函数
      head = a;
      tail = b;
      length = c;
      flag = d;
      p = new int[c];
      for(int i = 0;i < length;i++){
        p[i] = 0;
      }
    }
    void Sprint(){
      for(int j = 0;j <length;j++){
        cout<<p[j]<<endl;
      }
    }
    void PUSH(int x){//入栈
      if(flag == 1){
        if(tail == length){
          cout<<tail;
          tail = 0;
          if(tail == head){
            cout<<"上溢出!"<<head<<endl;
            tail = length;
          }else{
            p[length-1] = x;
          }
        }else{
          tail = tail+1;
          if(tail == head){
            cout<<"上溢出!"<<endl;
            tail = tail-1;
          }else{
            p[tail-1] = x;
          }
        }
      }else{
        tail = tail+1;
        p[head] = x;
        flag = 1;
      }
   }
    int POP(){//出栈
      int temp = tail;
      if(head != tail){
        if(tail != 0){
          tail--;
        }else{
          tail = length-1;
        }
        return p[tail];
      }else{
        cout<<"下溢出!"<<endl;
        tail = temp;
        return -1;
      }
    }
};
测试函数:
void main(){
  int num[] = {8,2,3,9,9,5,6,8,1,4,6,7,5};
  Q a(13); 
  for(int k = 0;k < 13;k++) a.ENQ(num[k]); 
  for(int b = 0;b < 13;b++) cout<<a.DEQ()<<endl;
  S m(13); 
   for(int i = 0;i < 13;i++)m.PUSH(num[i]); 
   for(int j = 0;j < 13;j++)cout<<m.POP()<<endl;
}

posted on 2013-09-26 21:07  程序猿猿猿  阅读(156)  评论(0编辑  收藏  举报

导航