[英]Insertion List Linked List Java {Debug}
您好,我試圖用Java編寫插入列表,但我似乎不知道自己是否有一個運行中的while循環,該循環沒有終止於類的sortInsertion方法中。 請幫助。
public class LinkedList {
public static void main(String[] args) {
LinkedList numbers = new LinkedList();
numbers.enqueue(12);
numbers.enqueue(4);
numbers.enqueue(11);
numbers.enqueue(8);
numbers.enqueue(10);
numbers.sortInsertion(numbers.startNode);
//System.out.println(s);
}
private int numValues;
private Node startNode;
private Node endNode;
private Node currNode;
/** Constructor for BoundedQueue
* @param inputSize maximum size of the Queue
*/
public LinkedList() {
numValues = 0;
}
/**
* @return the current number of element in Queue
* Useful for testing
*/
public int size() {
return numValues;
}
/** Adds a new value to the end of the queue
*
* @param value the integer to be added
*/
public void enqueue(int value) {
this.currNode = new Node(value);
if (this.startNode == null) {
this.startNode = this.currNode;
this.endNode = this.startNode;
} else {
this.endNode.next = this.currNode;
this.endNode = this.currNode;
}
numValues++;
}
public String toString(Node startNode) {
String s="";
Node trav = startNode;
while(trav != null) {
s += trav.value;
s+=",";
trav = trav.next;
}
return s;
}
public Node sortInsertion( Node head) {
if(head == null || head.next == null)
return head;
Node sort = null;
Node trav = null;
Node travSort = null;
Node prevSort = null;
sort = head;
trav = head.next;
sort.next = null;
while(trav != null) {
travSort = sort;
System.out.println(travSort.value);
while(travSort != null) {
if(travSort.value > trav.value) {
Node temp = trav;
temp.next = travSort;
travSort = temp;
if(prevSort != null) {
prevSort.next = travSort;
}
if(sort.value == travSort.value) {
sort = travSort;
}
break;
}
prevSort = travSort;
travSort = travSort.next;
//System.out.println(travSort.value);
}
trav = trav.next;
}
System.out.println(toString(sort));
return sort;
}
private class Node {
private int value;
private Node next;
public Node(int val) {
value = val;
next = null;
}
}
}
您似乎在以下幾行中創建了無休止的冗余:
Node temp = trav; (1)
temp.next = travSort; (2)
travSort = temp; (3)
因此temp == trav(1)但temp.next!= trav.next但temp.next == travSort(2)。 但是(3)設置travSort = temp
因此,travSort.next == temp.next == travSort
這就是while循環永不結束的原因,因為一旦輸入travSort,就永遠不能為null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.