我正在尝试创建一个将节点添加到我的链表的方法。该方法采用字符串。这是我创建的方法:
public void add(String x)
{
Node newNode = new Node();
newNode.element = x;
newNode.nextNode = firstNode;
firstNode = newNode;
}
不幸的是,此代码不起作用。有没有办法改变它以使其工作?
以下是我获得的所有信息:
具有 Node 内部类的链表类:
class LinkedList implements StringCollection
{
private static class Node
{
public String element;
public Node nextNode;
public Node (String element)
{
this.element = element;
this.nextNode = null;
}
}
private Node firstNode;
public NodeStringCollection ()
{
firstNode = null;
}
//add method goes here
public String toString ()
{
String s = "";
Node node = firstNode;
while (node != null)
{
s = s + node.element + " ";
node = node.nextNode;
}
return s;
}
}
测试的链接类:
Class Test
{
public static void main(String [] args)
{
StringCollection sc = new LinkedList ();
sc.add (new String ("A"));
sc.add (new String ("B"));
sc.add (new String ("C"));
sc.add (new String ("D"));
System.out.println (sc);
int countStrings = sc.size ();
System.out.println (countStrings);
}
}
输出
D C B A
4
我修复了你的代码。您做错的是,您添加到LinkedList
的元素替换了旧firstNode
。因此,添加到实现中的最后一个节点将成为新的第一个节点。因此,您的LinkedList
打印D C B A
这与应有的相反。
下面的代码存储第一个节点和最后一个节点。添加新节点时,我们让最后一个节点指向新创建的节点,然后将最后一个节点设置为新创建的节点:
法典
public class LinkedList {
public static class Node {
public String element;
public Node nextNode;
public Node(String element) {
this.element = element;
this.nextNode = null;
}
}
private Node firstNode;
private Node lastNode;
public LinkedList() {
firstNode = null;
lastNode = null;
}
public void add(String x) {
Node newNode = new Node(x);
if (firstNode == null)
firstNode = newNode;
if (lastNode != null)
lastNode.nextNode = newNode;
lastNode = newNode;
}
public String toString() {
String s = "";
Node node = firstNode;
while (node != null) {
s = s + node.element + " ";
node = node.nextNode;
}
return s;
}
}
示例代码
public static void main(String args[]) throws Exception {
LinkedList sc = new LinkedList();
sc.add(new String("A"));
sc.add(new String("B"));
sc.add(new String("C"));
sc.add(new String("D"));
System.out.println(sc);
}
输出
A B C D