添加方法不适用于Java中的链表

时间:2015-01-16 12:55:11

标签: java eclipse interface linked-list nodes

我正在尝试创建一个将节点添加到链接列表的方法。该方法采用String。这是我创建的方法:

    public void add(String x)
    {
        Node newNode = new Node();
        newNode.element = x;
        newNode.nextNode = firstNode;
        firstNode = newNode;
    }

不幸的是,此代码无效。有没有办法可以改变它以使其有效?

以下是我提供的所有信息:

带有节点内部类的链接列表类:

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

1 个答案:

答案 0 :(得分:0)

我修复了你的代码。您错误的是,您添加到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