-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinomialHeap.java
More file actions
99 lines (91 loc) · 3.28 KB
/
Copy pathBinomialHeap.java
File metadata and controls
99 lines (91 loc) · 3.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package BinomialHeap;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class BinomialHeap {
Node heapRoot;
public BinomialHeap(Node node){
this.heapRoot = node;
}
public BinomialHeap merge(BinomialHeap heap1, BinomialHeap heap2){
LinkedList<Node> nodeList = new LinkedList<>();
Node node1 = heap1.heapRoot;
Node node2 = heap2.heapRoot;
while (node1 != null && node2 != null){
if (node1.count > node2.count){
nodeList.add(node2);
node2 = node2.nextSibling;
}else {
nodeList.add(node1);
node1 = node1.nextSibling;
}
}
if (node1 != null){
nodeList.get(nodeList.size()-1).nextSibling = node1;
}else {
nodeList.get(nodeList.size()-1).nextSibling = node2;
}
return getBinomialHeap(nodeList);
}
public BinomialHeap unite(BinomialHeap heap){
Node node = heap.heapRoot;
List<Node> list = new ArrayList<>();
while (node != null) {
Node prevNode = node.previousSibling;
Node nextNode = node.nextSibling;
if (nextNode != null){
if (node.count != nextNode.count){
list.add(node);
node = node.nextSibling;
}else if (nextNode.nextSibling != null && nextNode.count == nextNode.nextSibling.count){
list.add(node);
node = node.nextSibling;
}else if (node.value <= nextNode.value){
Node temp = nextNode.nextSibling;
Node leftChild = node.leftMostChild;
node.leftMostChild = nextNode;
node.count += nextNode.count;
nextNode.nextSibling = leftChild;
node.nextSibling = temp;
list.add(node);
node = node.nextSibling;
}else {
Node leftChild = nextNode.leftMostChild;
nextNode.leftMostChild = node;
node.nextSibling = leftChild;
if (prevNode != null){
prevNode.nextSibling = nextNode;
}
nextNode.count += nextNode.leftMostChild.count;
node = nextNode;
list.add(nextNode);
node = node.nextSibling;
}
}
}
return getBinomialHeap(list);
}
public BinomialHeap add(BinomialHeap heap, Node node){
BinomialHeap newHeap = new BinomialHeap(node);
return unite(merge(heap, newHeap));
}
public BinomialHeap getBinomialHeap(List<Node> list){
Node node = list.get(0);
for (int i = 1; i < list.size(); i++){
node.nextSibling = list.get(i);
}
return new BinomialHeap(node);
}
}
class Node{
Node nextSibling;
Node previousSibling;
Node leftMostChild;
int value;
int count;
public Node(int value){
this.value = value;
count = 1;
nextSibling = previousSibling = leftMostChild = null;
}
}