[英]Doubly-linked list insertion sort function: Why isn't my insertion sort function inserting the last two integer inputs into my linked list?
[英]Why is my doubly-linked list repeating on insertion?
我的代碼生成了我無法完全理解的奇怪答案。 例如,我的insert方法似乎只是重復我進行的第一次插入,而無視列表的大小以及在列表之后進行的所有插入調用。
public class LinkedListImpl implements LIST_Interface {
Node sentinel;
private int numElts;
public LinkedListImpl(){
sentinel=new Node(0);
numElts = 0;
}
public boolean insert(double elt, int index) {
Node temp = new Node(elt);
Node currentNode;
int x;
if(index > size()) {
return false;
}
else if(index == 0){
currentNode = sentinel;
if(size() == 0) {
currentNode.prev = temp;
temp.next = sentinel;
}
currentNode.next = temp;
temp.prev = currentNode;
numElts++;
return true;
}
else {
currentNode = sentinel;
for(x = 0; x < index; x++) {
currentNode = currentNode.next;
}
temp = currentNode;
currentNode.prev = temp;
temp.next = currentNode;
numElts++;
return true;
}
}
public double get(int index) {
Node currentNode;
int x;
if(numElts == 0) {
return Double.NaN;
}
else {
currentNode = sentinel;
for(x = 0; x < index; x++) {
currentNode = currentNode.next;
}
return currentNode.getData();
}
}
}
public int size() {
return numElts;
}
這段代碼在這里:
LinkedListImpl L= new LinkedListImpl();
L.insert(45.0, 0);
L.insert(13.0, 1);
L.insert(89, 2);
System.out.println("Size of the list: " + L.size());
System.out.println(L.get(0));
System.out.println(L.get(1));
System.out.println(L.get(2));
System.out.println(L.get(3));
返回值:
Size of the list: 3
0.0
45.0
45.0
我不明白為什么45.0不是L.get(0)
的第一個條目
我也不明白為什么它會一遍又一遍地復制45.0。 如果我使用for循環將L.get(x)
打印為0 <= x <= 10
,則從x = 2
到x = 10
仍將重復45.0。
一方面,您沒有設置所有引用。 要將newNode
插入prevNode
和nextNode
之間的雙向鏈接中,您需要更改以下引用:
prevNode.next
newNode.prev
newNode.next
nextNode.prev
您的代碼僅設置其中的一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.