【发布时间】:2016-07-19 14:13:06
【问题描述】:
我在 JAVA 中创建了一个程序来将元素添加到 LinkedList 并在添加元素时对元素进行排序。我在排序时使用的 swap 技术类似于将节点添加到 LinkedList 的 beginning 时使用的技术。该技术适用于后一种情况,但无法在前一种情况下运行。我不明白为什么这不起作用。以下是我的代码供您参考。
//Node class
class Node{
int d; Node link;
Node(int d){
this.d = d;
link = null;
}
}//Node
//LinkedList class
class LL{
Node start;
LL(){
start = null;
}
//method to add and sort the nodes
//in ascending order of the values of 'd' of the nodes
void insert(Node nd){
if(start==null){
start = nd;
}
else{
Node temp = start;
while(temp!=null){
if(nd.d<=temp.d){
Node t2 = temp;
temp = nd;
nd.link = t2;
break;
}
temp = temp.link;
}
}
}//insert
//method to display nodes of the LinkedList
void display(){
Node temp = start;
do{
System.out.print(temp.d + " ");
temp = temp.link;
}while(temp!=null);
}//display
}//LL
//Main class
class LL_Test{
public static void main(String[] args){
LL myLL = new LL();
myLL.insert(new Node(5));
myLL.insert(new Node(2));
myLL.insert(new Node(7));
myLL.insert(new Node(6));
myLL.insert(new Node(1));
myLL.display();
}//main
}//LL_Test
预期输出:1 2 5 6 7
获得的输出:5
【问题讨论】:
标签: java sorting linked-list singly-linked-list