第二次資料結構試驗
#include <iostream> using namespace std; class SqStack { protected: int count; int maxSize; int *elems; bool Full() const; void Init(int size);
public: SqStack(int size = 10000); virtual ~SqStack(); int Length() const; bool Empty() const; void Clear(); void Traverse() const; bool Push(const int &e); bool Top(int &e) const; bool Pop(int &e); }; bool SqStack::Full() const { return count == maxSize; } void SqStack::Init(int size) { maxSize = size; if (elems != NULL) delete []elems; elems = new int[maxSize]; count = 0; } SqStack::SqStack(int size) { elems = NULL; Init(size); } SqStack::~SqStack() { delete []elems; } int SqStack::Length() const { return count; } bool SqStack::Empty() const { return count == 0; } void SqStack::Clear() { count = 0; } void SqStack::Traverse() const { for (int curPosition = 1; curPosition <= Length(); curPosition++) { cout<<elems[curPosition - 1]<<" "; } cout<<endl; } bool SqStack::Push(const int &e) { if (Full()) { return false; } else { elems[count++] = e; return true; } } bool SqStack::Top(int &e) const { if(Empty()) { return false; } else { e = elems[count - 1]; return true; } } bool SqStack::Pop(int &e) { if (Empty()) { return false; } else { e = elems[count - 1]; count--; return true; } } class SqQueue { protected: int front, rear; int maxSize; int *elems; bool Full() const; void Init(int size); public: SqQueue(int size = 1000); virtual ~SqQueue(); int Length() const; bool Empty() const; void Clear(); void Traverse() const; bool OutQueue(int &e); bool GetHead(int &e) const; bool InQueue(const int &e); }; bool SqQueue::Full() const { return Length() == maxSize - 1; } void SqQueue::Init(int size) { maxSize = size; if (elems != NULL) delete []elems; elems = new int[maxSize]; rear = front = 0; } SqQueue::SqQueue(int size) { elems = NULL; Init(size); } SqQueue::~SqQueue() { delete []elems; } int SqQueue::Length() const { return (rear - front + maxSize) % maxSize; } bool SqQueue::Empty() const { return rear == front; } void SqQueue::Clear() { rear = front = 0; } void SqQueue::Traverse() const { for (int curPosition = front; curPosition != rear; curPosition = (curPosition + 1) % maxSize) { cout<<elems[curPosition]<<" "; } cout<<endl; } bool SqQueue::OutQueue(int &e) { if (!Empty()) { e = elems[front]; front = (front + 1) % maxSize; return true; } else { return false; } } bool SqQueue::GetHead(int &e) const { if (!Empty()) { e = elems[front]; return true; } else { return false; } } bool SqQueue::InQueue(const int &e) { if (Full()) { return false; } else { elems[rear] = e; rear = (rear + 1) % maxSize; return true; } } int main() { ios_base::sync_with_stdio(0); int a[5]={1,2,3,4,5}; SqQueue b; SqStack c; int e; int n=5; for(int i=0;i<5;i++) b.InQueue(a[i]); cout<<"逆置前的元素順序:"<<endl; b.Traverse(); for(int i=0;i<5;i++) { b.OutQueue(e); c.Push(e); } for(int i=0;i<5;i++) { c.Pop(e); b.InQueue(e); } cout<<"逆置後的元素順序:"<<endl; b.Traverse(); }