我想在Java中为Heap数据结构创建一个类,允许用户选择MinHeap或MaxHeap
构造函数应如下所示:
public Heap(String type) { if (type.equals("min")) { //allow this object only to use methods for MinHeap } else { //allow this object only to use methods for MaxHeap } }
请注意,这两种方法的方法确实不同.例如,此方法在MaxHeaps中使用,并且不会在MinHeap中以相同的方式实现:
public void maxHeapify(int i, int n) { int l = leftPos(i); int r = rightPos(i); int largest; if (l < n && heap.get(l) > heap.get(i)) { largest = l; } else { largest = i; } if (r < n && heap.get(r) > heap.get(largest)) { largest = r; } if (largest != i) { swap(i, largest); maxHeapify(largest, n); } }
我使用数组来表示MaxHeap.
可能吗?或者我应该为MaxHeap和MinHeap创建单独的类; 各有其具体方法?或者您认为我应该遵循这样的方式:示例:
public void getMax() { if (type.equals("min")) { //use the method for MinHeap } else { //apply the method for MaxHeap } }
随意更改问题的标题因为我不知道究竟如何问它
你应该有一个Heap
带有两个实现类的接口 - MinHeap
和MaxHeap
.这就是Collections API的设计方式.例如,该List
接口有许多实现,其中一些包括LinkedList
和ArrayList
.