我在插入二项式堆时遇到问题,当我调用 insert 1 它打印 (1) 然后我插入 2 它显示 (2) 而不是 (1(2)) 然后显示三个 (3) 而不是 ( 3)(1(2))。如果有人可以帮助解决我的问题,我将不胜感激。先感谢您。这是我的代码
public class BHeap {
int key;
int degree;//The degree(Number of children)
BHeap parent, leftmostChild, rightmostChild, rightSibling,root,previous,next;
public BHeap(){
key =0;
degree=0;
parent =null;
leftmostChild=null;
rightmostChild=null;
rightSibling=null;
root=null;
previous=null;
next=null;
}
public BHeap merge(BHeap y){
BHeap newHeap = new BHeap();
BHeap currentHeap = y;
BHeap nextHeap = y.rightSibling;
while(currentHeap.rightSibling !=null){
if(currentHeap.degree==nextHeap.degree){
if(currentHeap.key<nextHeap.key){
if(currentHeap.degree ==0){
currentHeap.leftmostChild=nextHeap;
currentHeap.rightmostChild=nextHeap;
currentHeap.rightSibling=nextHeap.rightSibling;
nextHeap.rightSibling=null;
nextHeap.parent=currentHeap;
currentHeap.degree++;
}
else{
newHeap = currentHeap;
newHeap.rightmostChild.rightSibling=nextHeap;
newHeap.rightmostChild=nextHeap;
nextHeap.parent=newHeap;
newHeap.degree++;
nextHeap.rightSibling=null;
nextHeap=newHeap.rightSibling;
}
}
else{
if(currentHeap.degree==0){
nextHeap.rightmostChild=currentHeap;
nextHeap.rightmostChild.root = nextHeap.rightmostChild;//add
nextHeap.leftmostChild=currentHeap;
nextHeap.leftmostChild.root = nextHeap.leftmostChild;//add
currentHeap.parent=nextHeap;
currentHeap.rightSibling=null;
currentHeap.root=currentHeap;//add
nextHeap.degree++;
}
else{
newHeap=nextHeap;
newHeap.rightmostChild.rightSibling=currentHeap;
newHeap.rightmostChild=currentHeap;
currentHeap.parent= newHeap;
newHeap.degree++;
currentHeap=newHeap.rightSibling;
currentHeap.rightSibling=null;
}
}
}
else{
currentHeap=currentHeap.rightSibling;
nextHeap=nextHeap.rightSibling;
}
}
return y;
}
public void Insert(int x){
BHeap newHeap= new BHeap();
newHeap.key=x;
if(this.root==null){
this.root=newHeap;
}
else{
this.root = merge(newHeap);
}
}
public void Display(){
System.out.print("(");
System.out.print(this.root.key);
if(this.leftmostChild != null){
this.leftmostChild.Display();
}
System.out.print(")");
if(this.rightSibling!=null){
this.rightSibling.Display();
}
}
}