[英]How do I fix that infinite loop on a custom double linked list?
我創建了一個自定義 LinkedList 並且我正在嘗試使用一種基於值對其進行分區的方法。 沒有必要保持順序,所以我想將小於 x 的值添加到列表的頭部,並將值等於或大於尾部。
盡管如此,還是會發生無限循環,因為在檢查發生時 node.next 永遠不會為空。
這是代碼:
public class LinkedList<T extends Comparable<T>> {
private int size = 0;
private Node<T> head = null;
private Node<T> tail = null;
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
/**
*
* @param t the new element to be added at the end of the list
* NOTE: null items are not allowed
*
* @return true if added
*/
public boolean add(T t) {
if (t == null) {
return false;
}
// if head is null add as head
if (head == null) {
head = new Node<>(t, null, null);
tail = head;
} else {
Node<T> newTail = new Node<>(t, tail, null);
tail.next = newTail;
tail = newTail;
}
size++;
return true;
}
void partition(T value) {
Node<T> node = head;
while (node != null) {
Node<T> prev = node.previous;
Node<T> next = node.next;
if (node.data.compareTo(value) >= 1) {
// should go to tail
if (node != tail) {
prev.next = node.next;
next.previous = node.previous;
tail.next = node;
node.previous = tail;
node.next = null;
tail = node;
}
} else {
// should go to head
if (node != head) {
prev.next = node.next;
if (null != next) {
next.previous = node.previous;
}
head.previous = node;
node.next = head;
head = node;
}
}
node = next;
}
head.previous = null;
tail.next = null;
}
public T getFirst() {
return head.data;
}
public Node<T> getHead() {
return head;
}
public T getLast() {
return tail.data;
}
private static class Node<T extends Comparable<T>> {
T data;
Node<T> previous;
Node<T> next;
Node(T data, Node<T> previous, Node<T> next) {
this.data = data;
this.previous = previous;
this.next = next;
}
}
}
要重現的測試用例:
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Arrays;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class LinkedListTest {
private LinkedList<Integer> linkedList;
@BeforeMethod
public void setUp() {
linkedList = new LinkedList<>();
}
@Test
public void testPartition() {
linkedList.add(0);
linkedList.add(9);
linkedList.add(2);
linkedList.add(5);
linkedList.add(4);
linkedList.add(7);
linkedList.add(1);
int[] actual = new int[linkedList.size()];
linkedList.partition(5);
for (int i = 0; i < linkedList.size(); ++i) {
actual[i] = linkedList.get(i);
}
System.out.println(Arrays.toString(actual));
}
}
假設您的列表有兩個項目:A->B 以及 A 和 B > 值(因此“應該到尾”)。 開始你的代碼。 節點 A > 值,因此 A 位於尾部。 所以現在你的列表是 B->A,B 是“下一個”節點,A 現在是尾部。
循環的下一次迭代查看節點 B。節點 B > 值,因此 B 放在尾部。 現在您的列表是 A->B,A 是“下一個”節點,B 現在是尾部。 顯然這是一個無限循環。
要本着編寫此代碼的精神解決此問題,請在開始循環之前執行以下操作:
last_node = tail;
現在,就在你有node = next;
之前node = next;
做這個:
if(node == last_node) break;
在上面的例子中, last_node
指向 B。循環處理 A 然后 B 然后退出,因為 B 是last_node
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.