[英]Nodes not properly adding to LinkedList
我知道我不应该尝试重新发明轮子,但是我必须完成这项工作。 我正在努力从LinkedList中获取所有输出,我相信我的addFirst()方法未正确添加节点,或者我的toString()方法未正确显示LinkedList。 知道为什么吗? 我对此感到困惑,不确定是否可以在其他地方寻求帮助。
我没有任何错误,只是零输出。
主要:
public static void main(String args[]) {
LinkList theList = new LinkList();
theList.addFirst("One");
theList.getFirst();
theList.size();
theList.toString();
} // end main()
LinkList.java:
public class LinkList {
private Node first;
private Node current;
public LinkList() {
first = null;
current = first;
}
public boolean isEmpty() {
return (first == null);
}
public void removeFirst() {
try {
if (!isEmpty()) {
Node temp = first;
first = first.getNext();
}
} catch (NullPointerException e) {
}
}
public int size() {
int count = 0;
if (isEmpty()) {
return 0;
}
while (current != null) {
current = current.getNext();
count++;
}
return count;
}
@Override
public String toString() {
String str;
int size = size();
str = "Size: " + size;
str += "\nElements:";
while (current != null) {
for (int i = 0; i < size; i++) {
str += "\nNode: " + current.getNext();
}
}
return str;
}
public String getFirst() {
if (first == null) {
return null;
}
return first.getData();
}
public void addFirst(String data) {
Node newNode = new Node(data);
newNode.getNext();
first = newNode;
}
public boolean contains(String target) {
while (current != null) {
if (current.getData().equals(target)) {
return true;
}
current.getNext();
}
return false;
}
Node.java
public class Node {
private String data;
private Node next;
public Node(String data) {
this.data = data;
}
public String getData() {
return data;
}
public Node getNext() {
return next;
}
public void setData(String data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
public String toString() {
return "Node: " + getData();
}
}
您应该使用System.out.println();
在控制台中环绕要查看其输出的呼叫System.out.println();
,例如:
System.out.println(theList.size());
System.out.println(theList.toString());
请注意,您无需在第二行System.out.println(theList);
显式调用toString()
方法System.out.println(theList);
自动调用theList
的toString()
方法,它等效于System.out.println(theList.toString());
。
在您的addFirst()
方法中,您应该:
first
一个节点设置为新节点的下一个节点 first
您缺少上述步骤之一。
另外,所有包含迭代列表的方法( toString()
, size()
等)都需要先使用current = first;
进行初始化current = first;
在迭代开始之前。 否则current
可以为null
,并且迭代将不会开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.