java 链表 addLast 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6165330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linked list addLast method
提问by Moj
How can I build an addLast
method in Java? I already know LinkedList
has a built-in method which does this)
如何addLast
在 Java 中构建方法?我已经知道LinkedList
有一个内置方法可以做到这一点)
This is what I've tried:
这是我尝试过的:
public void addFirst(int d1, double d2) {
Link link = new Link(d1, d2);
link.nextLink = first;
first = link;
}
public void addLast(int d1 , double d2){
Link v = new Link(d1, d2);
v.nextLink = null;
tail.nextLink = v;
tail = v
}
}
public void printList() {
Link currentLink = first;
System.out.print("List: ");
while(currentLink != null) {
currentLink.printlink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
My addFirst
method works, but I don't know how to connect them.
我的addFirst
方法有效,但我不知道如何连接它们。
in the main :
在主要:
LinkList list = new LinkList();
list.addFirst(4, 4.04);
list.addFirst(5, 5.05);
list.addlast(3,4.5);
list.printList();
回答by Woot4Moo
I realize that this is a school assignment so without giving the answer here are the steps to follow:
我意识到这是一项学校作业,所以这里没有给出答案,以下是要遵循的步骤:
- check if list is empty
- if list is empty set head + tail to point to same node
- Iterate over all elements
- Update tail to new node
- 检查列表是否为空
- 如果列表为空,则设置 head + tail 指向同一节点
- 迭代所有元素
- 更新尾部到新节点
Also there is no way that the addFirst method you have above would work you are constantly resetting the value in tail.
此外,您上面的 addFirst 方法也无法正常工作,您会不断重置 tail 中的值。
回答by pfhayes
Your problem appears to be in the last line. You want
您的问题似乎在最后一行。你要
tail = v;
Not
不是
v = tail;
Furthermore, You have
此外,你有
tail = link
as the last line of your addFirst method - it's not clear why you're doing this. You shouldn't need to update the tail of the list as you add to the front.
作为 addFirst 方法的最后一行 - 不清楚你为什么要这样做。当您添加到前面时,您不需要更新列表的尾部。
回答by kin
public void addLast(int d1, double d2){
Node node = new Node(d1, d2);
Node temp = first;
while(temp.next!= null) {
temp = temp.next;
}
temp.next = node;
}