队列类,以及优先队列类的实现
之前学了c++,但是学得非常非常非常的不系统,怎么说了,一是自己囫囵吞枣的看书本上的知识,然后的话呢,与C相比而言,c++还是多了许多特性的,自己用C++写类还是不太会,比如类的派生,继承,虚函数,复制构造函数,构造函数,析构函数…等一系列特性让我觉得脑壳疼。最近,学校开的软工课需要用数据结构,于是自己学着封装了队列类和优先队列类。
小根堆
class Heap {//堆,维护
private:
enum {H_SIZE = 20};
Pair heap[H_SIZE];
const int hsize;//堆的最大容量
int Size;//当前堆的容量
public:
Heap(int hs = H_SIZE);
~Heap();
void Swap(Pair &elem1, Pair &elem2);
bool push(Pair elem);
bool pop(Pair &elem);
bool gettop(Pair &elem) const;
int heapcount() const;
bool isempty() const;
bool isfull() const;
};
Heap::Heap(int hs) : hsize(hs){
Size = 0;
}
Heap::~Heap() {
}
void Heap::Swap(Pair &elem1, Pair &elem2) {
Pair tmp;
tmp = elem2;
elem2 = elem1;
elem1 = tmp;
return;
}
bool Heap::push(Pair elem) {//相当于建堆
if (Size == hsize) {//堆满
return false;
}
heap[++Size] = elem;
for (int i = Size; i > 1; i /= 2) {
if (heap[i].second < heap[i/2].second) {//大于父亲节点
Swap(heap[i], heap[i/2]);
}
}
return true;
}
bool Heap::pop(Pair &elem) {//取堆顶元素,并重新调整堆的结构
if (Size == 0) {//堆空
return false;
}
elem = heap[1];
heap[1] = heap[Size--];
for (int i = 1; 2*i + 1 <= Size;) {
if (heap[2*i].second < heap[2*i + 1].second) {//左儿子小于右儿子
if (heap[i].second > heap[2*i].second) {
Swap(heap[i], heap[2*i]);
i = 2*i;
}
else return true;
} else {
if (heap[i].second > heap[2*i+1].second) {
Swap(heap[i], heap[2*i+1]);
i = i*2 + 1;
}
else return true;
}
if (i * 2 == Size) {
if (heap[i].second > heap[Size].second)
Swap(heap[i], heap[Size]);
}
}
return true;
}
bool Heap::isempty() const{
if (Size == 0)
return true;
return false;
}
bool Heap::isfull() const{
if (Size == hsize)
return true;
return false;
}
int Heap::heapcount() const{
return Size;
}
bool Heap::gettop(Pair &elem) const {
if (Size >= 1) {
elem = heap[1];
return true;
}
return false;
}
队列
struct customer {
Item item;
struct customer *next;
};
class Queue {
private:
enum {Q_SIZE = 100};//队列的最大容量
//customer Node;
int No;//当前队列元素的序号
customer *Front;//头指针
customer *Rear;//尾指针
public:
const int qsize;//队列的容量
public:
Queue(int qs = Q_SIZE);
~Queue();
bool isempty() const;
bool isfull() const;
int queuecount() const;
bool enqueue(const Item &q);
bool dequeue(Item &q);
};
Queue::Queue(int qs ) : qsize(qs){//构造函数
Rear = nullptr;
Front = nullptr;
No = 0;
}
Queue::~Queue() {
customer *tmp;
while (Front != nullptr) {
tmp = Front;
Front = Front -> next;
delete tmp;
}
}
bool Queue::isempty() const {
if (No == 0)
return true;
return false;
}
bool Queue::isfull() const{
if (No == qsize)
return true;
return false;
}
bool Queue::enqueue(const Item &q) {
if (isfull())
return false;
customer *add = new customer;
add -> item = q;
add -> next = nullptr;
No++;
if (Front == nullptr)
Front = add;
else
Rear -> next = add;
Rear = add;
return true;
}
bool Queue::dequeue(Item &q) {
if (Front == nullptr)
return false;
q = Front -> item;
No--;
customer *tmp = Front;
Front = Front -> next;
delete tmp;
if (No == 0)
Rear = nullptr;
return true;
}
int Queue::queuecount() const {
return No;
}