|
|
@ -122,32 +122,34 @@ class MaxHeap {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* Driver Code */
|
|
|
|
/* Driver Code */
|
|
|
|
/* 初始化大顶堆 */
|
|
|
|
if (require.main === module) {
|
|
|
|
const maxHeap = new MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
|
|
|
|
/* 初始化大顶堆 */
|
|
|
|
console.log('\n输入列表并建堆后');
|
|
|
|
const maxHeap = new MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
|
|
|
|
maxHeap.print();
|
|
|
|
console.log('\n输入列表并建堆后');
|
|
|
|
|
|
|
|
maxHeap.print();
|
|
|
|
/* 获取堆顶元素 */
|
|
|
|
|
|
|
|
let peek = maxHeap.peek();
|
|
|
|
/* 获取堆顶元素 */
|
|
|
|
console.log(`\n堆顶元素为 ${peek}`);
|
|
|
|
let peek = maxHeap.peek();
|
|
|
|
|
|
|
|
console.log(`\n堆顶元素为 ${peek}`);
|
|
|
|
/* 元素入堆 */
|
|
|
|
|
|
|
|
const val = 7;
|
|
|
|
/* 元素入堆 */
|
|
|
|
maxHeap.push(val);
|
|
|
|
const val = 7;
|
|
|
|
console.log(`\n元素 ${val} 入堆后`);
|
|
|
|
maxHeap.push(val);
|
|
|
|
maxHeap.print();
|
|
|
|
console.log(`\n元素 ${val} 入堆后`);
|
|
|
|
|
|
|
|
maxHeap.print();
|
|
|
|
/* 堆顶元素出堆 */
|
|
|
|
|
|
|
|
peek = maxHeap.pop();
|
|
|
|
/* 堆顶元素出堆 */
|
|
|
|
console.log(`\n堆顶元素 ${peek} 出堆后`);
|
|
|
|
peek = maxHeap.pop();
|
|
|
|
maxHeap.print();
|
|
|
|
console.log(`\n堆顶元素 ${peek} 出堆后`);
|
|
|
|
|
|
|
|
maxHeap.print();
|
|
|
|
/* 获取堆大小 */
|
|
|
|
|
|
|
|
const size = maxHeap.size();
|
|
|
|
/* 获取堆大小 */
|
|
|
|
console.log(`\n堆元素数量为 ${size}`);
|
|
|
|
const size = maxHeap.size();
|
|
|
|
|
|
|
|
console.log(`\n堆元素数量为 ${size}`);
|
|
|
|
/* 判断堆是否为空 */
|
|
|
|
|
|
|
|
const isEmpty = maxHeap.isEmpty();
|
|
|
|
/* 判断堆是否为空 */
|
|
|
|
console.log(`\n堆是否为空 ${isEmpty}`);
|
|
|
|
const isEmpty = maxHeap.isEmpty();
|
|
|
|
|
|
|
|
console.log(`\n堆是否为空 ${isEmpty}`);
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export { MaxHeap };
|
|
|
|
export { MaxHeap };
|
|
|
|