这是作业,但请知道我已经在线寻找帮助(如http://www.sethi.org/classes/class_stuff/cis435/others/notes-java/data/collections/lists/simple-linked-list.html)和我的教科书,但我仍然有一些问题。在Java中帮助制作一个单独链接的列表
任何帮助,将不胜感激......
现在我想只是插入值,但没有什么工作。不管它是第一个项目,它是作为最后一个添加还是添加在其中。
Node header = null; // First element of list.
Node back = null; // Last element of list.
public void insert(int i, double value){ //insert value before i-th element
Node e = new Node();
e.num = value;
Node curr = header;
for(int x=0;x<i;x++) {
if (i == 1) { //we want to insert as first thing
if (size == 0) { //its the FIRST time we add something
header.next = e;
e.next = back;
break;
} else if (size == 1){
e.next = header.next; //i.e. the second thing in the list
header.next = e;
break;
} else {
e.next = header.next.next; //i.e. the second thing in the list
header.next = e;
break;
}
}
else if (x == (i-1)) {
e.next = curr.next;
curr.next = e;
break;
}
curr = curr.next;
}
size = size+1;
}
不知道为什么它不起作用。
谢谢!
定义为“not working” – wheaties 2010-09-21 01:04:36
这对于'insert in i'来说代码太多了。有两件事情:1)如果可以这样构造节点:'Node node = new Node(val);'2)使逻辑更简单。将它分解为:A)查找插入的节点,或者抛出异常/返回null(无论约定是什么),B)执行插入(事实上,这应该是节点类本身的一种方法。应该分割“Node”和“LinkedList”类之间的责任)。顺便说一下,LL的标准名称应该是“head”和“tail”,而不是“header”和“back”。想想蛇,不是Excel。什么是头部? – 2010-09-21 01:11:29
@Harnish - 很棒的评论。 +1仅用于“这对于我来说插入的代码太多”。发现。 – duffymo 2010-09-21 01:18:57