您好我正在尝试在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;
}
}
}
答案 0 :(得分:0)
看起来您在以下几行中创建了一个无休止的冗余:
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就永远不会为空。