码迷,mamicode.com
首页 > 其他好文 > 详细

左式堆

时间:2017-04-24 14:08:49      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:lis   row   void   public   ==   ret   int   cep   左式堆   

package com.iflytek.heap;

/**
 * 左式堆
 * @author fgtian
 *
 */
public class LeftListHeap {
	public static class HeapNode {
		int mValue;
		int mNpl = 0;
		HeapNode mLeftChild;
		HeapNode mRightChild;
	}
	
	HeapNode mRoot = null;
	
	public void insert(int value) {
		HeapNode node = new HeapNode();
		node.mValue = value;
		merge(node);
	}
	
	public int delMin() {
		if (null == mRoot) {
			throw new NullPointerException("null == mRoot");
		}
		int value = mRoot.mValue;
		mRoot = merge(mRoot.mLeftChild, mRoot.mRightChild);
		return value;
	}
	
	public void merge(HeapNode node) {
		mRoot = merge(mRoot, node);
		if (npl(mRoot.mRightChild) > npl(mRoot.mLeftChild)) {
			HeapNode l = mRoot.mLeftChild;
			mRoot.mLeftChild = mRoot.mRightChild;
			mRoot.mRightChild = l;
		}
		mRoot.mNpl = Math.min(npl(mRoot.mLeftChild), npl(mRoot.mRightChild)) + 1;
	}
	
	public void merge(LeftListHeap heap) {
		merge(heap.mRoot);
	}
	
	public static int npl(HeapNode h) {
		if (null == h) {
			return -1;
		}
		return h.mNpl;
	}
	
	public static HeapNode merge(HeapNode h1, HeapNode h2) {
		if (null == h1) {
			return h2;
		} else if (h2 == null) {
			return h1;
		} else { // 两个都不是null
			int v1 = h1.mValue;
			int v2 = h2.mValue;
			if (v1 <= v2) { // 拿他的
				h1.mRightChild = merge(h1.mRightChild, h2);
				if (npl(h1.mLeftChild) < npl(h1.mRightChild)) {
					HeapNode node = h1.mLeftChild;
					h1.mLeftChild = h1.mRightChild;
					h1.mRightChild = node;
				}
				h1.mNpl = Math.min(npl(h1.mLeftChild), npl(h1.mRightChild)) + 1;
				return h1;
			} else {
				h2.mRightChild = merge(h1, h2.mRightChild);
				if (npl(h2.mLeftChild) < npl(h2.mRightChild)) {
					HeapNode node = h2.mLeftChild;
					h2.mLeftChild = h2.mRightChild;
					h2.mRightChild = node;
				}
				h2.mNpl = Math.min(npl(h2.mLeftChild), npl(h2.mRightChild)) + 1;
				return h2;
			}
		}
	}
}

左式堆

标签:lis   row   void   public   ==   ret   int   cep   左式堆   

原文地址:http://www.cnblogs.com/jzdwajue/p/6756358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!