I am constructing a class "dequeint" of integers and using circular queue storage. I get my code to compile but its output is garbage?

Please HELP!
.h

#include <iostream.h>
#include <stdlib.h>

const int MAXSIZE = 10;
typedef int NodeType;

class dequeint {

private:
       NodeType NodeArray[MAXSIZE];
       int headi; //head in NodeArray
       int tailsucci; // index of one element beyond tail
public:
       dequeint(void) {headi=tailsucci=0;}
       void push_back(NodeType x) {
       if( ((tailsucci+1)%MAXSIZE) !=headi) {
           NodeArray[tailsucci]=x;
         tailsucci = (tailsucci +1) % MAXSIZE;
      }
   }
       void push_front(NodeType x) {
       if( ((tailsucci+1)%MAXSIZE) !=headi) {
           NodeArray[headi]=x;
         headi = (headi +1) % MAXSIZE;
      }
   }  
      void pop_front(void) {
      if( tailsucci != headi )  //if cqueue not empty
         headi = (headi + 1) % MAXSIZE;
   }  
      void pop_back(void) {
      if( tailsucci != headi )  //if cqueue not empty
         tailsucci = (tailsucci + 1) % MAXSIZE;
   }
      void print (void) {
      cout << "deque: ";
      for(int i=headi; i!=tailsucci; i = (i + 1) % MAXSIZE)
         cout << NodeArray[i] << "  ";
      cout << "rear of queue  " << endl;
  }
};

.cpp

#include "deque.h"

int main(void) {
dequeint x;
x.print();
x.push_front(30);  x.print();
x.push_front(20);  x.print();
x.push_front(10);  x.print();
x.push_back(40);  x.print();
x.push_back(50);  x.print();
x.push_back(60);  x.print();
x.pop_front();  x.print();
x.pop_back();  x.print();
x.push_front(100); x.print();
x.push_back(200); x.print();
x.pop_front(); x.pop_front(); x.pop_front();
x.pop_front(); x.pop_front(); x.pop_front(); 
x.pop_front(); //should do nothing (and not crash)
cout << "push Enter to quit\n"; cin.get();

This: ((tailsucci+1)%MAXSIZE) !=headi is wrong.

Figure out why.


One problem you have is that if tailsucci and headi are both equal, you can't tell whether the buffer is full or empty. You should store the number of elements in the buffer, instead of storing the value tailsucci, because that's an easy way to avoid this ambiguity.

I am not quite sure how to go about doing that. Maybe some more explanation is needed for me to corret that problem. How am I going to store the elements in the buffer?

Maybe I'm not being very clear. I'm saying, suppose your class began with the following:

class dequeint {

private:
       NodeType NodeArray[MAXSIZE];
       int headi; // index of first element: 0 <= headi < MAXSIZE
       int length; // number of elements: 0 <= length <= MAXSIZE
public:

How would you implement it then?

You can see that if your version contained say, 0 in both headi, you'd have no way of knowing if the length was 0 or MAXSIZE.

This question has already been answered. Start a new discussion instead.