栈与队列实现

围绕两点,加深对栈与队列的理解

1 如何用两个栈实现一个队列

2 如何用两个队列实现一个栈

栈与队列 C++ 简易实现

  1 typedef int DataType;

  2 //简易栈

  3 class stack

  4 {

  5 private:

  6     enum {size=10};

  7     DataType element[size];

  8     int top; //指向栈顶

  9 public:

 10     stack():top(0) {}

 11     bool empty() { return top == 0; }

 12     bool full() { return top == size; }

 13     bool push (const DataType data);

 14     const DataType & pop();

 15 };

 16 bool stack::push (const DataType data)

 17 {

 18     if (full())

 19     {

 20         return false;

 21     }

 22     element[top++] = data;

 23     return true;

 24 }

 25 const DataType & stack::pop()

 26 {

 27     if (empty())

 28     {

 29         return -1;

 30     }

 31     return    element[--top];    

 32 }

 33 //简易队列

 34 class Queue

 35 {

 36 private:

 37     struct Node

 38     {

 39         DataType data;

 40         Node * next;

 41     };

 42     Node * front; //队头

 43     Node * rear;  //队尾

 44     int length;

 45     const int qsize;

 46     Queue(const Queue & q):qsize(0) {}  //防止滥用拷贝,与赋值

 47     Queue & operator=(const Queue & q) { return *this; }

 48 public:

 49     Queue(int qs);

 50     ~Queue();

 51     bool empty()const        { return front == rear;}

 52     bool full()const        { return length == qsize;}

 53     int getlength()const    { return length;}

 54     bool enqueue(const DataType &data);

 55     bool dequeue();

 56 };

 57 Queue::Queue(int qs):qsize(qs),length(0)

 58 {

 59     front = new Node;

 60     front->next = NULL;

 61     rear = front;

 62 }

 63 Queue::~Queue()

 64 {

 65     for (Node *p = front; p != NULL; )

 66     {

 67         Node *pTemp = p->next;

 68         delete p;

 69         p = pTemp;

 70     }

 71     front = rear = NULL;

 72 }

 73 bool Queue::enqueue(const DataType &data)

 74 {

 75     if (full())

 76     {

 77         return false;

 78     }

 79     Node *p = new Node;

 80     p->data = data;

 81     p->next = NULL;

 82     rear->next = p;

 83     rear = p;

 84     ++length;

 85     return true;

 86 }

 87 bool Queue::dequeue()

 88 {

 89     if (empty())

 90     {

 91         return false;

 92     }

 93     Node *p = front->next->next;

 94     delete front->next;

 95     front->next = p;

 96     if (p == NULL)

 97     {

 98         rear = front;

 99     }

100     --length;

101     return true;

102 }

 

你可能感兴趣的:(队列)