java - 附加到 Java 中的链表
问题描述
代码编译并运行,但 addToEnd 方法不起作用,这对我来说似乎是正确的,但我不确定错误在哪里,有人可以指导我需要修复代码的内容或位置
这是我的其他课程的代码
public class LinkedList {
private Node head;
/**
* constructor
* pre: none
* post: A linked list with a null item has been created.
*/
public LinkedList() {
head = null;
}
/**
* Activity: finds size of the Linked List.
* Pre-Condition: none
* Post-Condition: The size of the list is returned
*/
public int size() {
int counter = 0;
Node current = head;
while(current != null) {
counter++;
current = current.getNext();
}
return counter;
}
/**
* Adds a node to the end of the linked list.
* pre: String parameter
* post: The linked list has a new node at the end.
*/
public void addAtEnd(String s) {
Node current = head;
Node newNode = new Node(s);
if(head == null) {
head = newNode;
head.setNext(null);
}
else {
while(current.getNext() == null) {
current.setNext(newNode);
current = newNode;
}
}
}
private class Node {
private String data;
private Node next;
/**
* constructor
* pre: none
* post: A node has been created.
*/
public Node(String newData) {
data = newData;
next = null;
}
/**
* The node pointed to by next is returned
* pre: none
* post: A node has been returned.
*/
public Node getNext() {
return(next);
}
/**
* The node pointed to by next is changed to newNode
* pre: none
* post: next points to newNode.
*/
public void setNext(Node newNode) {
next = newNode;
}
/**
* The node pointed to by next is returned
* pre: none
* post: A node has been returned.
*/
public String getData() {
return(data);
}
}
}
这是我的主类代码,Blume 和 Dahl 从未被添加到列表中:
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addAtFront("Sachar");
list.addAtFront("Osborne");
list.addAtFront("Suess");
System.out.println("List has " + list.size() + " items.");
System.out.println(list);
list.addAtEnd("Blume");
list.addAtEnd("Dahl");
System.out.println(list);
}
}
解决方案
while (current.getNext() == null) {
current.setNext(newNode);
current = newNode;
}
这是不正确的;因为您没有跟踪列表的尾部,所以您需要遍历整个列表,然后添加newNode
到末尾(我相信您已经理解了)。为此,只需继续设置current
为current.getNext()
until current.getNext()
is null
,然后调用current.setNext(newNode);
Node next;
while ((next = current.getNext()) != null) {
current = next;
}
current.setNext(newNode);
推荐阅读
- php - 使用 PHP 循环更新记录
- python - 为什么此代码仅更改列表的某些元素而不更改其他元素?
- c# - 在切换到其他控件之前,如何将数据保存在用户控件上?
- mysql - MySQL - 为什么这个运行缓慢的查询没有使用(似乎是)正确的索引?
- jquery - 为什么 Kendo UI DatePicker 在通过 POST 提交的表单上没有将值传递给 JSP?
- java - 在 weblogic 12c 上部署应用程序失败
- sql - 带有多个连接的子选择的 Oracle 更新
- linux - 将窗口名称添加到屏幕截图 - 在快捷键中执行 bash 命令
- erp - 实时普及数据库缺失数据的复制和备份
- android - 如何在 android 中关闭或释放 AWSAppSyncClient