最近邻、k紧邻、范围查询
本文采用java对其进行实现,代码中关于Deque双端队列数据结构是本人实现的,
package LuoSen.DS.Tree.Distance;
/**用具KD树中的临近查询*/
public interface KDDistance {
/**返回两个数据之间的距离*/
public double HPointToHPointDistance(S a,S b);
/**返回指定高维数据指定维度之间的垂直距离*/
public double HPointToHPointDistanceInIDemision(S a,S b,byte i);
}
package LuoSen.DS.Tree;
public class KDTreeNode {
/**左子结点*/
public KDTreeNode left=null;
/**右子结点*/
public KDTreeNode right=null;
/**父结点*/
public KDTreeNode parent=null;
/**表示结点是否被删除*/
public boolean isRemoved=false;
/**当前所在的维度*/
public byte i=0;
/**结点数据*/
public S data;
/**默认构造函数*/
public KDTreeNode() {
}
/**根据数据构造*/
public KDTreeNode(S data) {
super();
this.data = data;
}
/**是否为叶子节点*/
public boolean isLeaf(){
return (left==null&&right==null);
}
/**删除树*/
public void clear()
{
left=null;
right=null;
isRemoved=false;
data=null;
}
@Override
public String toString() {
return ""+data;
}
}
package LuoSen.DS.Tree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import LuoSen.DS.DS.BinaryHeap;
import LuoSen.DS.DS.Deque;
import LuoSen.DS.DS.Stack;
import LuoSen.DS.Exceptions.IllegalParameterException;
import LuoSen.DS.Tree.Distance.KDDistance;
public class KDTree implements Iterable {
/** 根节点 */
private KDTreeNode root = null;
/** 树终结点的数目 */
private int size = 0;
/** 树的维度 */
private int k = 0;
/** k个维度的比较器列表 */
private ArrayList
/**计算两个数据之间的距离*/
private KDDistance kdd=null;
public KDTree(int k) {
root = new KDTreeNode();
root.parent = root;
this.k = k;
}
public ArrayList
return cp;
}
public void setCp(ArrayList
this.cp = cp;
}
public KDDistance getKdd() {
return kdd;
}
public void setKdd(KDDistance kdd) {
this.kdd = kdd;
}
public void buildKDTree(List datas) {
if (datas == null || datas.isEmpty())
return;
if (datas.size() == 1) {
this.insert(datas.get(0));
return;
}
int i = 0;
Collections.sort(datas, cp.get(i));
S mid = datas.get(datas.size() / 2 - 1);
this.insert(mid);
i++;
i %= k;
if (datas.size() >= 2) {
buildKDTree(datas.subList(0, datas.size() / 2 - 1), i);
buildKDTree(datas.subList(datas.size() / 2, datas.size()), i);
} else {
buildKDTree(datas, i);
}
}
private void buildKDTree(List datas, int i) {
if (datas == null || datas.isEmpty())
return;
if (datas.size() == 1) {
this.insert(datas.get(0));
return;
}
Collections.sort(datas, cp.get(i));
S mid = datas.get(datas.size() / 2 - 1);
this.insert(mid);
i++;
i %= k;
if (datas.size() >= 2) {
buildKDTree(datas.subList(0, datas.size() / 2 - 1), i);
buildKDTree(datas.subList(datas.size() / 2, datas.size()), i);
} else {
buildKDTree(datas, i);
}
}
/** 插入数据 ,如果data==null返回false,若已存在关键字相同的数据会替换*/
public boolean insert(S data) {
if (data == null)
return false;
if (size == 0) {
root.data = data;
root.i=0;
root.isRemoved=false;
size++;
return true;
} else {
return insert(root, data, 0);
}
}
/** 插入数据,如果data==null返回false */
private boolean insert(KDTreeNode kdtn, S data, int i) {
KDTreeNode newNode = null;
if (cp.get(i).compare(data, kdtn.data) < 0) {
if (kdtn.left == null) {
newNode = new KDTreeNode(data);
kdtn.left = newNode;
newNode.parent = kdtn;
newNode.i=(byte) (++i%k);
size++;
return true;
} else {
i++;
i %= k;
return insert(kdtn.left, data, i);
}
} else if (cp.get(i).compare(data, kdtn.data) > 0) {
if (kdtn.right == null) {
newNode = new KDTreeNode(data);
kdtn.right = newNode;
newNode.parent = kdtn;
newNode.i=(byte) (++i%k);
size++;
return true;
} else {
i++;
i %= k;
return insert(kdtn.right, data, i);
}
} else {
if (kdtn.isRemoved) {
kdtn.data = data;
kdtn.isRemoved=false;
size++;
return true;
}
if (this.isEquals(kdtn.data, data)) {
kdtn.data=data;
return true;
} else {
if (kdtn.left == null) {
newNode = new KDTreeNode(data);
kdtn.left = newNode;
newNode.parent = kdtn;
newNode.i=(byte) (++i%k);
size++;
return true;
} else {
i++;
i %= k;
return insert(kdtn.left, data, i);
}
}
}
}
/** 删除数据 */
public boolean remove(S data) {
if (data == null || size == 0)
return false;
return remove(root, data, 0);
}
/** 删除数据 */
private boolean remove(KDTreeNode kdtn, S data, int i) {
if (cp.get(i).compare(data, kdtn.data) < 0) {
if (kdtn.left == null) {
return false;
} else {
i++;
i %= k;
return remove(kdtn.left, data, i);
}
} else if (cp.get(i).compare(data, kdtn.data) > 0) {
if (kdtn.right == null) {
return false;
} else {
i++;
i %= k;
return remove(kdtn.right, data, i);
}
} else {
if (this.isEquals(kdtn.data, data)) {
if (kdtn.isRemoved)
return false;
kdtn.isRemoved = true;
size--;
if (kdtn.isLeaf()) {
if (kdtn != root) {
if (kdtn.parent.left == kdtn)
kdtn.parent.left = null;
else
kdtn.right = null;
}
}
return true;
} else {
if (kdtn.left == null) {
return false;
} else {
i++;
i %= k;
return remove(kdtn.left, data, i);
}
}
}
}
/** 查询对应对数关键字所对应的节点 */
public KDTreeNode search(S data) {
if (size == 0 || data == null)
return null;
return search(root, data, 0);
}
/** 查询对应对数关键字所对应的节点 */
private KDTreeNode search(KDTreeNode kdtn, S data, int i) {
if (cp.get(i).compare(data, kdtn.data) < 0) {
if (kdtn.left == null) {
return null;
} else {
i++;
i %= k;
return search(kdtn.left, data, i);
}
} else if (cp.get(i).compare(data, kdtn.data) > 0) {
if (kdtn.right == null) {
return null;
} else {
i++;
i %= k;
return search(kdtn.right, data, i);
}
} else {
if (this.isEquals(kdtn.data, data)) {
if(kdtn.isRemoved)
return null;
else
return kdtn;
} else {
if (kdtn.left == null) {
return null;
} else {
i++;
i %= k;
return search(kdtn.left, data, i);
}
}
}
}
/** 先序遍历KD树,返回迭代器,迭代器中元素为S类型 */
public Iterator PreOrderTraverse() {
Deque a = new Deque();
this.PreOrderTraverse(root, a);
return new AbstractTreeDataIterator(this, a);
}
/** 先序遍历KD树 */
protected void PreOrderTraverse(KDTreeNode S, Deque a) {
if (S != null) {
if(!S.isRemoved)
a.frontEnQueue(S.data);
this.PreOrderTraverse(S.left, a);
this.PreOrderTraverse(S.right, a);
}
}
/** 中序遍历KD树,返回迭代器,迭代器中元素为S类型 */
public Iterator InOrderTraverse() {
Deque a = new Deque();
this.InOrderTraverse(root, a);
return new AbstractTreeDataIterator(this, a);
}
/** 中序遍历KD树 */
protected void InOrderTraverse(KDTreeNode S, Deque a) {
if (S != null) {
this.InOrderTraverse(S.left, a);
if(!S.isRemoved)
a.frontEnQueue(S.data);
this.InOrderTraverse(S.right, a);
}
}
/** 后序遍历KD树,返回迭代器,迭代器中元素为S类型 */
public Iterator PostOrderTraverse() {
Deque a = new Deque();
this.PostOrderTraverse(root, a);
return new AbstractTreeDataIterator(this, a);
}
/** 后序遍历KD树 */
protected void PostOrderTraverse(KDTreeNode S, Deque a) {
if (S != null) {
this.PostOrderTraverse(S.left, a);
this.PostOrderTraverse(S.right, a);
if(!S.isRemoved)
a.frontEnQueue(S.data);
}
}
/** 先序遍历KD树,返回迭代器,迭代器中元素为KDTreeNode类型 */
public Iterator
Deque
this.PreOrderNodeTraverse(root, a);
return new AbstractTreeNodeDataIterator
}
/** 先序遍历KD树 */
protected void PreOrderNodeTraverse(KDTreeNode S, Deque
if (S != null) {
if(!S.isRemoved)
a.frontEnQueue(S);
this.PreOrderNodeTraverse(S.left, a);
this.PreOrderNodeTraverse(S.right, a);
}
}
/** 中序遍历KD树,返回迭代器,迭代器中元素为KDTreeNode类型 */
public Iterator
Deque
this.InOrderNodeTraverse(root, a);
return new AbstractTreeNodeDataIterator
}
/** 中序遍历KD树 */
protected void InOrderNodeTraverse(KDTreeNode S, Deque
if (S != null) {
this.InOrderNodeTraverse(S.left, a);
if(!S.isRemoved)
a.frontEnQueue(S);
this.InOrderNodeTraverse(S.right, a);
}
}
/** 后序遍历KD树,返回迭代器,迭代器中元素为KDTreeNode类型 */
public Iterator
Deque
this.PostOrderNodeTraverse(root, a);
return new AbstractTreeNodeDataIterator
}
/** 后序遍历KD树 */
protected void PostOrderNodeTraverse(KDTreeNode S, Deque
if (S != null) {
this.PostOrderNodeTraverse(S.left, a);
this.PostOrderNodeTraverse(S.right, a);
if(!S.isRemoved)
a.frontEnQueue(S);
}
}
/** 判断树种是否存在关键字和data相同的数据结点 */
public boolean contains(S data) {
return search(data) != null ? true : false;
}
/** 返回KD树的深度 */
public int getDepth()// 返回KD树的深度
{
return this.coutDepth();
}
/** 返回KD树节点的数目 */
public int getNodeNum()// 返回KD树节点的数目
{
return size;
}
/** 计算KD树的深度 */
protected int coutDepth() {
int depth = this.coutDepth(this.root);
return depth == 0 ? 0 : depth - 1;
}
/** 计算KD树的深度 */
protected int coutDepth(KDTreeNode S) {
if (S == null)
return 0;
int h1 = this.coutDepth(S.left);
int h2 = this.coutDepth(S.right);
return (Math.max(h1, h2) + 1);
}
/** 删除树 */
public void clear() {
root.clear();
}
/** 判断KD树是否为空 */
public boolean isEmpty() {
if (this.root == null || this.root.data == null)
return true;
return false;
}
/** 转化为字符串 */
public void toString(KDTreeNode kdtn, StringBuilder sb) {
if (kdtn != null) {
if (!kdtn.isRemoved && kdtn.data != null)
sb.append(kdtn).append("\n");
toString(kdtn.left, sb);
toString(kdtn.right, sb);
}
}
/** 先序转化为字符串 */
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("树中结点的数目:" + size + "\n");
toString(root, sb);
return sb.toString();
}
/** 抽象树的数据的迭代器 */
public static class AbstractTreeDataIterator implements Iterator {
private Deque D = null;
private KDTree tree;
public AbstractTreeDataIterator(KDTree tree, Deque D) {
this.tree = tree;
this.D = D;
}
@Override
public boolean hasNext() {
return !D.isEmpty();
}
@Override
public S next() {
return D.rearDequeue();
}
@Override
public void remove() {
S a = D.rearDequeue();
tree.remove(a);
}
}
/** 抽象树的结点的迭代器 */
public static class AbstractTreeNodeDataIterator implements Iterator {
private Deque D = null;
private KDTree tree;
public AbstractTreeNodeDataIterator(KDTree tree, Deque D) {
this.tree = tree;
this.D = D;
}
@Override
public boolean hasNext() {
return !D.isEmpty();
}
@Override
public S next() {
return D.rearDequeue();
}
@Override
public void remove() {
KDTreeNode a = (KDTreeNode) D.rearDequeue();
tree.remove(a.data);
}
}
/**判断两个数据的所有关键是否都相等*/
public boolean isEquals(S a,S b){
if(a==null||b==null)
return false;
for(Comparator c:cp){
if(c.compare(a, b)!=0)
return false;
}
return true;
}
/**最临近查询,首先设置计算节点之间距离的距离计算器
* @throws IllegalParameterException */
public S nearest(S data) throws IllegalParameterException{
if(data==null||size==0)
return null;
if(this.kdd==null)
throw new IllegalParameterException("请先设置计算距离的计算器!");
BinaryHeap
nearest(root,data,bp,1);
return bp.pop().data;
}
/**最临近查询,首先设置计算节点之间距离的距离计算器
* @throws IllegalParameterException */
public List nearest(S data,int k) throws IllegalParameterException{
if(data==null||size==0)
return null;
if(this.kdd==null)
throw new IllegalParameterException("请先设置计算距离的计算器!");
BinaryHeap
nearest(root,data,bp,k);
List ll=new LinkedList();
Stack s=new Stack();
while(!bp.isEmpty()){
s.push(bp.pop().data);
}
for(S sa:s){
ll.add(sa);
}
return ll;
}
/**给定半径和原点,索索该范围内所有点
* @throws IllegalParameterException */
public List inCircle(S p,double d) throws IllegalParameterException{
List ll=new LinkedList();
inCircle(root,p,ll,d);
return ll;
}
/**得到当前结点的上一个同维结点*/
public KDTreeNode getAboveSameDemisionNode(KDTreeNode kdtn){
byte i=kdtn.i;
kdtn=kdtn.parent;
while(kdtn!=root){
if(kdtn.i==i){
return kdtn;
}
kdtn=kdtn.parent;
}
if(kdtn.i==i)
return kdtn;
else
return null;
}
/**最临近查询,首先设置计算节点之间距离的距离计算器
* @throws IllegalParameterException */
private void inCircle(KDTreeNode kdtn,S data,List bp,double d) throws
IllegalParameterException{
if(kdtn!=null){
double dd=0.0;
double d1=0.0;
dd=kdd.HPointToHPointDistance(kdtn.data,data);
if(dd>d){
d1=kdd.HPointToHPointDistanceInIDemision
(data,kdtn.data,kdtn.i);
if(d1
inCircle(kdtn.left,data,bp,d);
inCircle(kdtn.right,data,bp,d);
}else if(d1==d){
if(cp.get(kdtn.i).compare(kdtn.data, data)>0){
inCircle(kdtn.left,data,bp,d);
}else{
inCircle(kdtn.right,data,bp,d);
}
}else{
KDTreeNode tn=this.getAboveSameDemisionNode(kdtn);
if(tn==null){
if(cp.get(kdtn.i).compare(kdtn.data, data)>0){
inCircle(kdtn.left,data,bp,d);
}else{
inCircle(kdtn.right,data,bp,d);
}
}else{
dd=kdd.HPointToHPointDistanceInIDemision(data,tn.data,tn.i);
if(d
if(cp.get(kdtn.i).compare(kdtn.data, tn.data)>0){
if(cp.get(kdtn.i).compare(kdtn.data, data)>0){
inCircle(kdtn.left,data,bp,d);
}else{
inCircle(kdtn.right,data,bp,d);
}
}else{
if(cp.get(kdtn.i).compare(kdtn.data, data)>0){
inCircle(kdtn.left,data,bp,d);
}else{
inCircle(kdtn.right,data,bp,d);
}
}
}else{
if(cp.get(kdtn.i).compare(kdtn.data, tn.data)>0){
inCircle(kdtn.left,data,bp,d);
}else{
inCircle(kdtn.right,data,bp,d);
}
}
}
}
}else{
if(!kdtn.isRemoved){
bp.add(kdtn.data);
}
inCircle(kdtn.left,data,bp,d);
inCircle(kdtn.right,data,bp,d);
}
}
}
/**最临近查询,首先设置计算节点之间距离的距离计算器
* @throws IllegalParameterException */
private void nearest(KDTreeNode kdtn,S data,BinaryHeap
k) throws IllegalParameterException{
if(kdtn!=null){
double d=0.0;
double dd=0.0;
double d1=0.0;
if(bp.size()
if(!kdtn.isRemoved){
bp.add(kdtn);
}
nearest(kdtn.left,data,bp,k);
nearest(kdtn.right,data,bp,k);
}else{
dd=kdd.HPointToHPointDistance(kdtn.data,data);
d=kdd.HPointToHPointDistance(data,bp.getTopElement().data);
if(dd>d){
d1=kdd.HPointToHPointDistanceInIDemision
(data,kdtn.data,kdtn.i);
if(d1
nearest(kdtn.left,data,bp,k);
nearest(kdtn.right,data,bp,k);
}else if(d1==d){
if(cp.get(kdtn.i).compare(kdtn.data, data)>0){
nearest(kdtn.left,data,bp,k);
}else{
nearest(kdtn.right,data,bp,k);
}
}else{
KDTreeNode tn=this.getAboveSameDemisionNode(kdtn);
if(tn==null){
if(cp.get(kdtn.i).compare(kdtn.data, data)>0){
nearest(kdtn.left,data,bp,k);
}else{
nearest(kdtn.right,data,bp,k);
}
}else{
dd=kdd.HPointToHPointDistanceInIDemision(data,tn.data,tn.i);
if(d
if(cp.get(kdtn.i).compare(kdtn.data, tn.data)>0){
if(cp.get(kdtn.i).compare(kdtn.data, data)>0){
nearest(kdtn.left,data,bp,k);
}else{
nearest(kdtn.right,data,bp,k);
}
}else{
if(cp.get(kdtn.i).compare(kdtn.data, data)>0){
nearest(kdtn.left,data,bp,k);
}else{
nearest(kdtn.right,data,bp,k);
}
}
}else{
if(cp.get(kdtn.i).compare(kdtn.data, tn.data)>0){
nearest(kdtn.left,data,bp,k);
}else{
nearest(kdtn.right,data,bp,k);
}
}
}
}
}else{
if(!kdtn.isRemoved){
bp.pop();
bp.add(kdtn);
}
nearest(kdtn.left,data,bp,k);
nearest(kdtn.right,data,bp,k);
}
}
}
}
/**查询在指定范围之内的数据集合region是查询区域*/
public List queryDataInRegion(KDRegion region){
List ll=new LinkedList();
queryDataInRegion(root,region,ll);
return ll;
}
/**查询在指定范围之内的数据集合*/
private void queryDataInRegion(KDTreeNode kdtn,KDRegion region,List
ll){
if(kdtn!=null){
if(!kdtn.isRemoved&&isInRegion(kdtn.data,region)){
ll.add(kdtn.data);
}
if(!region.low[kdtn.i]||cp.get(kdtn.i).compare(kdtn.data,region.start)>=0)
queryDataInRegion(kdtn.left,region,ll);
if(!region.high[kdtn.i]||cp.get(kdtn.i).compare(kdtn.data,region.end)<0)
queryDataInRegion(kdtn.right,region,ll);
}
}
/**判断指定节点是否在指定区域里*/
public boolean isInRegion(S data,KDRegion r){
for(int i=0;i
if(!r.low[i]&&!r.high[i]){
continue;
}else if(!r.low[i]&&r.high[i]){
if(cp.get(i).compare(data, r.end)>0)
return false;
}else if(r.low[i]&&!r.high[i]){
if(cp.get(i).compare(data, r.start)<0)
return false;
}else if(r.low[i]&&r.high[i]){
if(cp.get(i).compare(data, r.end)>0||cp.get(i).compare(data, r.start)<0)
return false;
}
}
return true;
}
/**判断对应的两个闭区域是否有交集*/
public boolean isIntercect(KDRegion r1,KDRegion r2){
for(int i=0;i
if((cp.get(i).compare(r1.start, r2.start)>0&&cp.get(i).compare(r1.start,
r2.end)<0)
||(cp.get(i).compare(r2.start, r1.start)>0
&&cp.get(i).compare(r2.start, r1.end)<0))
return true;
}
return false;
}
/**返回迭代器*/
@Override
public Iterator iterator() {
return this.InOrderTraverse();
}
**************************************************************************************************************************************************************
/**计算高位数据巨臂比较器*/
public class HPointCP implements Comparator
private S data;
public HPointCP(S a) {
super();
this.data = a;
}
@Override
public int compare(KDTreeNode a, KDTreeNode b) {
double d1=0.0,d2=0.0;
d1=KDTree.this.kdd.HPointToHPointDistance(data, a.data);
d2=KDTree.this.kdd.HPointToHPointDistance(b.data,data);
if(d1
return 1;
else if(d1>d2)
return -1;
else
return 0;
}
}
/**查询在指定范围之内的数据集合s,e分别表示高位区域,low,hight标示对应维度是否有
上下界*/
public static class KDRegion{
/**标示左边界*/
public S start;
/**标示右边界*/
public S end;
/**标示对应维度是否有约束*/
public boolean []low;
/**标示对应维度是否有约束*/
public boolean []high;
public KDRegion() {
super();
}
public S getS() {
return start;
}
public void setS(S s) {
this.start = s;
}
public S getE() {
return end;
}
public void setE(S e) {
this.end = e;
}
public boolean[] getLow() {
return low;
}
public void setLow(boolean[] low) {
this.low = low;
}
public boolean[] getHigh() {
return high;
}
public void setHigh(boolean[] high) {
this.high = high;
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package LuoSen.DS.DS;
import LuoSen.DS.Alg.Util.CreateComparator;
import LuoSen.DS.Exceptions.IllegalParameterException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
*
* @author 雒森
*/
/**
* 基于动态数组实现的二叉堆,根据比较器的结果,决定是大根堆,还是小根堆当比较器的
比较方法
* >时返回1,=返回0,<返回-1就是小跟堆,,当S是可比较的数据时可以不传入比较器否
则要传入对应的比较器
*/
public class BinaryHeap implements Iterable, Serializable {
/** 存储数据的动态数组 */
protected ArrayList data;
/** 堆中数据的个数 */
protected int num;
/** 比较器 */
protected Comparator cp;
/** 构造函数初始化 */
public BinaryHeap() {
data = new ArrayList(100);
num = 0;
cp = null;
}
/** 构造函数初始化 */
public BinaryHeap(Comparator cp) throws IllegalParameterException {
data = new ArrayList(100);
num = 0;
if (cp == null)
throw new IllegalParameterException("输入的参数不合法!");
this.cp = cp;
}
/** 构造函数初始化 */
public BinaryHeap(S datas[]) throws IllegalParameterException {
data = new ArrayList(100);
num = 0;
if (datas == null)
throw new IllegalParameterException("输入的参数不合法!");
else {
if (Comparable.class.isAssignableFrom(datas[0].getClass())) {
CreateComparator cc = new CreateComparator();
cp = cc.getComparator();
} else {
cp = null;
}
this.add(datas);
}
}
/** 构造函数初始化 */
public BinaryHeap(S datas[], Comparator cp)
throws IllegalParameterException {
data = new ArrayList(100);
num = 0;
if (datas == null || cp == null)
throw new IllegalParameterException("输入的参数不合法!");
else {
this.cp = cp;
this.add(datas);
}
}
/** 设置比较器 */
public void setComparator(Comparator cp) {
this.cp = cp;
}
/** 返回比较器 */
public Comparator getComparator() {
return cp;
}
/** 判断堆是否为空 */
public boolean isEmpty() {
return num == 0;
}
/** 返回堆的大小 */
public int size() {
return num;
}
/** 获取列表数据 */
public List getDatas() {
return this.data;
}
/** 返回二叉堆中的第i个数据(i从1开始) */
public S getIndex(int i) throws IllegalParameterException {
if (i < 1 || i > num) {
throw new IllegalParameterException("输入的参数不合法!");
} else
return data.get(i);
}
/** 向上浮动函数 */
public void shiftUp(int hole) {
if (hole == 1)
return;
S a = this.data.get(hole);
for (; hole > 1 && cp.compare(a, data.get(hole / 2)) < 0; hole /= 2)
{
data.set(hole, data.get(hole / 2));
}
data.set(hole, a);
}
/** 向下过滤函数 */
public void percolateDown(int hole) {
S a = data.get(hole);
int child = 0;
for (; hole * 2 <= num; hole = child) {
child = hole * 2;
if (child != num
&& cp.compare(data.get(child + 1),
data.get(child)) < 0) {
child++;
}
if (cp.compare(data.get(child), a) < 0) {
data.set(hole, data.get(child));
} else
break;
}
data.set(hole, a);
}
/** 获取堆顶元素 */
public S getTopElement() {
return data.get(1);
}
/** 向堆中插入元素 */
public void add(S a) throws IllegalParameterException {
if (a == null)
throw new IllegalParameterException("输入的参数不合法!");
else {
if (cp == null) {
if (Comparable.class.isAssignableFrom(a.getClass())) {
CreateComparator cc = new
CreateComparator();
cp = cc.getComparator();
} else {
cp = null;
}
}
if (cp == null)
throw new IllegalParameterException("比较器为null值!
");
++num;
if (data.isEmpty())
data.add((S) new Object());
while (data.size() < num + 1)
data.add(a);
data.set(num, a);
this.shiftUp(num);
}
}
/** 向堆中加入元素 */
public final void add(S datas[]) throws IllegalParameterException {
if (datas == null)
throw new IllegalParameterException("输入的参数不合法!");
else {
for (int i = 0; i < datas.length; i++) {
this.add(datas[i]);
}
}
}
/** 返回迭代器 */
@Override
public Iterator iterator() {
return this.data.listIterator(1);
}
/** 从堆中弹出顶部元素,并删除 */
public S pop() {
if (num <= 0)
return null;
S min = data.get(1);
delete(1);
return min;
}
/** 从堆中删除位于i>=1&&i
public S delete(int index) {
if (index > num || index < 1 || num <= 0)
return null;
S a = data.get(index);
S b = data.get(num);
data.set(index, data.get(num--));
if (cp.compare(a, b) > 0)
this.shiftUp(index);
else
this.percolateDown(index);
return a;
}
/** 将二叉堆调整为当前大小 */
public void trimToSize() {
data.trimToSize();
}
@Override
public String toString() {
StringBuilder a = new StringBuilder("2叉堆中的元素依次为:\n[");
for (int i = 1; i < num; i++)
a.append(" ").append(data.get(i)).append(",");
if (num > 0)
a.append(data.get(num)).append(" ]");
else
a.append("堆为空]");
return a.toString();
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package LuoSen.DS.AbstractInterface;
import java.io.Serializable;
/**
*
* @author LENOVO
*/
/**抽象迭代器或遍历器接口*/
public interface Iterator extends java.util.Iterator , Serializable
{
/**返回前一个元素*/
public S prior();
/**判断是否存在前一个元素*/
public boolean hasPrior();
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package LuoSen.DS.DS;
import LuoSen.DS.AbstractInterface.Iterator;
import java.io.Serializable;
/**
*
* @author luosen
*/
/**此数据类型为栈和队列中的数据元素类型*/
public class Data implements Iterable,Serializable
{
/**数据元素可以是任何数据类型*/
protected S data;//数据元素
/**当前元素的下一个元素的引用*/
protected Data next;//当前元素的下一个元素的引用
/**当前元素的前一个元素的引用*/
protected Data prior;//当前元素的下一个元素的引用
/**默认构造函数*/
public Data()
{
this.data=null;
this.next=null;
this.prior=null;
}
/**设置当前对象的数据*/
public void setData(S data)
{
this.data=data;
}
/**返回当前对象的数据*/
public S getData()
{
return this.data;
}
/**设置当前对象的下一个结点的引用*/
public void setNext(Data next)
{
this.next=next;
}
/**返回当前对象的下一个结点的引用*/
public Data getNext()
{
return this.next;
}
/**设置当前对象的前一个结点的引用*/
public void setPrior(Data prior)
{
this.prior=prior;
}
/**返回当前对象的前一个结点的引用*/
public Data getPrior()
{
return this.prior;
}
/**判断数据是否相等*/
@Override
public boolean equals(Object o)
{
if(this==o)
return true;
if(o==null||!(o instanceof Data))
return false;
Data a=(Data)o;
if(this.data.equals(a.data))
return true;
return false;
}
@Override
public int hashCode()
{
int hash = 7;
hash = 71 * hash + (this.data != null ? this.data.hashCode() : 0);
return hash;
}
/**返回遍历器*/
@Override
public Iterator iterator()
{
Data c=this;
class DataIterator implements Iterator
{
Data cur;
public DataIterator(Data c)
{
cur=c;
}
@Override
public S next()
{
cur=cur.getNext();
return cur.getData();
}
@Override
public S prior()
{
cur=cur.getPrior();
return cur.getData();
}
@Override
public boolean hasNext()
{
if(cur.getNext()!=null)
return true;
return false;
}
@Override
public boolean hasPrior()
{
if(cur.getPrior()!=null&&cur.getPrior().getData()!=null)
return true;
return false;
}
@Override
public void remove()
{
if(cur!=null&&cur.getPrior()!=null)
{
if(cur.getNext()!=null)
{
cur.getPrior().setNext(cur.getNext());
cur.getNext().setPrior(cur.getPrior());
cur=cur.getPrior();
}
else
{
cur=cur.getPrior();
cur.setNext(null);
}
}
else if(cur!=null&&cur.getPrior()==null&&cur.getData()!=null)
{
cur=null;
}
}
}
DataIterator iterator=new DataIterator(c);
return iterator;
}
/**将当前对象的字符串表示*/
@Override
public String toString()
{
String a="";
a+=this.data;
return a;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package LuoSen.DS.DS;
import LuoSen.DS.AbstractInterface.Iterator;
import java.io.Serializable;
/**
*
* @author luosen
*/
/**此类型为双向队列*/
public class Deque implements Iterable,Serializable
{
/**指向对头的引用*/
protected Data front;//指向对头的引用
/**指向队尾的引用*/
protected Data rear;//指向队尾的引用
/**队列的长度*/
protected int size;//队列的长度
/**构造一个空队列*/
public Deque()//构造一个空队列
{
front=new Data();
rear=front;
this.front.setNext(null);
size=0;
}
/**返回队列的长度*/
public int length()//返回队列的长度
{
return this.size;
}
/**返回指向队首元素的数据,若队为空,返回null*/
public S getFrontData()//返回指向队首元素的数据
{
if(this.front.getNext()==null)
return (S) this.front.getNext().getData();
return null;
}
/**返回指向队首元素的引用,若队为空,返回null*/
public Data getFront()//返回指向队首元素的引用
{
return this.front.getNext();
}
/**返回指向队尾元素的数据,若队为空,返回null*/
public S getRearData()//返回指向队尾元素的数据
{
return (S) this.rear.getData();
}
/**返回指向队尾元素的引用,若队为空,返回null*/
public Data getRear()//返回指向队尾元素的引用
{
return this.rear;
}
/**判断队列是否为空,若为空返回true否则返回false*/
public boolean isEmpty()//判断队列是否为空
{
if(this.front==this.rear)
return true;
return false;
}
/**销毁队列*/
public void clear()//销毁队列
{
if(this.isEmpty()!=true)
{
this.rear=this.front;
this.front.setNext(null);
this.size=0;
System.gc();
}
}
/**从队尾将数据data进队*/
public void rearEnQueue(S data)//尾进队
{
Data a=new Data();
if(a==null)
System.exit(1);
a.setData(data);
a.setPrior(rear);
this.rear.setNext(a);
this.rear=a;
this.size++;
}
/**从队首将数据data进队*/
public void frontEnQueue(S data)//前进队
{
Data a=new Data();
if(a==null)
System.exit(1);
a.setData(data);
a.setNext(this.front.getNext());
if(a.getNext()!=null)
a.getNext().setPrior(a);
else
this.rear=a;
a.setPrior(this.front);
this.front.setNext(a);
this.size++;
}
/**从队首出队并返回删除的那个数据,若队为空返回null*/
public S frontDequeue()//前出队并返回删除的那个数据
{
if(this.isEmpty()!=true)
{
S a=(S) this.front.getNext().getData();
Data b=this.front.getNext();
this.front.setNext(b.getNext());
if(b.getNext()!=null)
b.getNext().setPrior(b.getPrior());
else
this.rear=this.front;
this.size--;
return a;
}
return null;
}
/**从队尾出队并返回删除的那个数据,若队为空返回null*/
public S rearDequeue()//后出队并返回删除的那个数据
{
if(this.isEmpty()!=true)
{
S a=(S) this.getRear().getData();
this.rear=this.rear.getPrior();
this.rear.setNext(null);
this.size--;
return a;
}
return null;
}
/**判断当前队列与队列a是否相等,若相等返回true否则返回false*/
@Override
public boolean equals(Object o)
{
if(this==o)
return true;
if(o==null||!(o instanceof Deque))
return false;
Deque a=(Deque)o;
Data cur1=this.front.getNext();
Data cur2=a.front.getNext();
while(cur1!=null&&cur2!=null)
{
if(cur1.getData().equals(cur2.getData())!=true)
return false;
cur1=cur1.getNext();
cur2=cur2.getNext();
}
if(cur1==null&&cur2==null)
return true;
return false;
}
@Override
public int hashCode() {
int hash = 3;
hash = 11 * hash + (this.front != null ? this.front.hashCode() : 0);
hash = 11 * hash + (this.rear != null ? this.rear.hashCode() : 0);
hash = 11 * hash + this.size;
return hash;
}
/**返回遍历器*/
@Override
public Iterator iterator()
{
if(this.front!=null)
return this.front.iterator();
return null;
}
/**将队列对象转化为字符串*/
@Override
public String toString()//将队列对象转化为字符串
{
StringBuilder a=new StringBuilder("队列里的元素从顶到底依次为:\n");
int i=1;
Data current=this.front.getNext();
if(current==null)
a.append("此队列为空队列");
while(current!=null)
{
a.append("\n第").append(i).append("个元素为:").append(current.getData());
i++;
current=current.getNext();
}
return a.toString();
}
}