# 算法导论2nd 10.1-7

2019/05/14 17:20

#include <iostream>

class Queue
{
int *array;

Queue(Queue &&q) = delete;
Queue(const Queue &q) = delete;
Queue &operator=(const Queue &q) = delete;

public:
Queue(int n)
{
size = n + 1;
array = new int [size];
tail = 0;
}

~Queue()
{
if (array)
{
delete [] array;
array = NULL;
size = -1;
tail = -1;
}
}

bool enqueue(int x)
{
if (full())
return false;
array[tail++] = x;
if (tail >= size)
tail = 0;
return true;
}

bool dequeue(int &res)
{
if (empty())
return false;
return true;
}

bool empty()
{
}

bool full()
{
return (tail + 1) % size == head;
}
};

class Stack
{
Queue q1, q2, *pusher, *poper;
int size;

public:
Stack(int n) : q1(n), q2(n)
{
pusher = &q1;
poper = &q2;
}

bool push(int x)
{
if (poper->full())
return false;
pusher->enqueue(x);
while (poper->dequeue(x))
pusher->enqueue(x);
Queue *tmp = pusher;
pusher = poper;
poper = tmp;
return true;
}

bool pop(int &res)
{
return poper->dequeue(res);
}
};

int main()
{
int t;
Queue queue(4);
queue.enqueue(1);
queue.dequeue(t);
queue.enqueue(2);
queue.dequeue(t);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
queue.enqueue(6);
queue.enqueue(7);
while (queue.dequeue(t))
std::cout << t << std::endl;
queue.enqueue(8);
queue.enqueue(9);
queue.enqueue(10);
queue.enqueue(11);
queue.enqueue(12);
while (queue.dequeue(t))
std::cout << t << std::endl;
Stack stack(4);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
while(stack.pop(t))
std::cout << t << std::endl;
return 0;
}

0
0 收藏

0 评论
0 收藏
0