我想創造一個堆結構,每個節點有2個數據,1)字符串2)int 所以我認爲每個節點必須是一個名爲「heapNode」的類,但我在交換方法中遇到了麻煩, 請幫我怎樣才能實現一個堆,每個節點是一個類?
import java.util.ArrayList;
public class MainHeap {
ArrayList<heapNode> heap;
MainHeap(){
new ArrayList<heapNode>();
}
public int getMin(){
return heap.get(0).data ;
}
private int parent(int pos) {
return pos/2;
}
private void swap(int pos1, int pos2) {
heapNode temp =new heapNode();
temp = heap.get(pos1);
heap.get(pos1) = heap.get(pos2);
heap.get(pos2) = temp;
}
public void insert(int elem) {
int max = heap.size();
heap.get(max).data = elem ;
int current = heap.size() ;
while (heap.get(current).data < heap.get(parent(current)).data){
swap (current , parent(current));
}
}
}
,這是我heapNode類
public class heapNode {
int data;
String fileName;
}
交換方法有錯誤,但我不能解決錯誤
非常感謝你能看到我下面的代碼我徘徊,如果它是真的還是假的私人無效掉期(INT POS1,POS2 INT){ \t \t \t heapNode臨時=新heapNode(); \t \t \t臨時= heap.get(POS1); \t \t \t heap.remove(POS1); \t \t \t heap.add(POS1,heap.get(POS2)); \t \t \t heap.remove(pos2); \t \t \t heap.add(pos2,temp); \t \t} – Rojin