面向对象的简易栈,队列实现
//顺序栈 class Stack { private: int size; int top; char *st; public: Stack(int); bool push(char e); bool pop(char &e); }; Stack::Stack(int msize) { size = msize; top = -1; st = new char[size]; } bool Stack::push(char e) { if (top == size - 1) { cout << "栈满" << endl; return false; } else { st[++top] = e; return true; } } bool Stack::pop(char &c) { if (top == -1) { cout << "栈空" << endl; return false; } else { c = st[top--]; return true; } } //链式栈 class LNode { public: char data; LNode *next; }; class LStack { public: LStack(); bool push(char e); bool pop(char &e); private: LNode *top; }; LStack::LStack() { top = NULL; } bool LStack::push(char e) { LNode *ptr = new LNode; ptr->data = e; ptr->next = top; top = ptr; return true; } bool LStack::pop(char &e) { if (top == NULL) { cout << "栈空" << endl; return false; } else { LNode *ptr = top; e = top->data; top = top->next; delete ptr; return true; } } //顺序队 class Queue { private: int MaxSize; int front; int rear; char *qu; public: Queue(int size); bool enQueue(char e); bool deQueue(char &e); }; Queue::Queue(int size) { MaxSize = size; rear = front = 0; qu = new char[MaxSize]; } bool Queue::enQueue(char e) { if ((rear + 1) % MaxSize == front) { cout << "队满" << endl; return false; } rear = (rear + 1) % MaxSize; qu[rear] = e; return true; } bool Queue::deQueue(char &e) { if (rear == front) { cout << "队空" << endl; return false; } front = (front + 1) % MaxSize; e = qu[front]; return true; } //链队 class LQueue { private: LNode *front; LNode *rear; public: LQueue(); bool enQueue(char e); bool deQueue(char &e); }; LQueue::LQueue() { front = rear = NULL; } bool LQueue::enQueue(char e) { LNode *p = new LNode; p->data = e; p->next = NULL; if (rear == NULL) rear = front = p; else { rear->next = p; rear = p; } return true; } bool LQueue::deQueue(char &e) { LNode *p; if (rear == NULL) { cout << "队空" << endl; return false; } else p = front; if (front == rear) { front = rear = NULL; } else front = front->next; e = p->data; delete p; return true; }