Change the previous lab to display a min-heap as an indented list (level numbers included). In order to do this you will have to add two new member functions to the heap class - void _printIndented(int index, void visit(int, int)); // A - void printIndented(void visit(int, int)); // B Note: One function would be sufficient(A). However, to make the call simpler, a wrapper function (B) has been added (to "hide" the root of the heap). Another solution is to add level as a parameter to _printIndented: - void _printIndented(int index, int level, void visit(int, int));
54 lines
1.2 KiB
C++
54 lines
1.2 KiB
C++
/*
|
|
This program will
|
|
- read integers from the keyboard and insert them into a min-heap,
|
|
- display the min-heap as an indented list (level numbers included) and
|
|
- display the integers as they are deleted from the heap.
|
|
*/
|
|
|
|
#include <iostream>
|
|
#include "Heap.h"
|
|
|
|
using namespace std;
|
|
|
|
void iDisplay(int item, int level);
|
|
|
|
int main() {
|
|
Heap heap;
|
|
|
|
// build heap
|
|
int num;
|
|
cout << "Enter integers [0 - to stop]" << endl;
|
|
cin >> num;
|
|
while (num != 0) {
|
|
heap.insertHeap(num);
|
|
cin >> num;
|
|
}
|
|
cout << "Heap capacity: " << heap.getSize() << endl;
|
|
cout << "Heap actual number of elements: " << heap.getCount() << endl;
|
|
|
|
heap.printIndented(iDisplay);
|
|
|
|
// print items as they are deleted from the heap (sorted)
|
|
if (heap.isEmpty())
|
|
cout << "N/A";
|
|
while (!heap.isEmpty()) {
|
|
heap.deleteHeap(num);
|
|
cout << num << " ";
|
|
}
|
|
cout << endl;
|
|
|
|
return 0;
|
|
}
|
|
|
|
|
|
/*
|
|
indented display:
|
|
displays one item including the level number
|
|
and corresponding indentation
|
|
*/
|
|
void iDisplay(int item, int level) {
|
|
for (int i = 0; i < level; i++)
|
|
cout << "..";
|
|
cout << level << "). " << item << endl;
|
|
}
|