0

我正在创建一个链接列表的实现,并且在使用 add 方法时遇到了问题。在用几个条目对其进行测试后,我的size()方法总是返回 1。我做错了什么。

public class Node {

    public int data;
    public Node next;

       public Node(int data){
        this.data = data;
    }       
}


public class LinkedList {

    public Node first;
    public Node last;

    public LinkedList(){
        first = null;
        last = null;
    } 

    public void add(int data){    
        Node newNode = new Node(data);
        if(first == null){
            first = newNode;        
        } else {
            add(first, newNode);
        }                  
    }

    public void add(Node currentNode, Node newNode){

        if(currentNode.next != null){
            add(currentNode.next, newNode);
        }
        currentNode.next = newNode;
    }   
        public int size(){        
        if(first == null){
            return 0;
        }
        else{
            return size(first);
        }        
    }
    public int size(Node currentNode){
        //Count Starts At One Because First = 1.
        int count = 1;        
        if(currentNode == null){
            return count;
        }
        else {
            count++;
            return size(currentNode.next);
        }             
    }
}
4

2 回答 2

1

您忘记了else2-arg 形式的add. 就目前而言,

if(currentNode.next != null){
    add(currentNode.next, newNode);
}
currentNode.next = newNode;

将始终将新节点添加到列表first 的所有其他节点。如果currentNode.next = newNode出现在一个else子句中,它只会被正确地添加到末尾。

此外,您的size方法总是返回1,因为最终分支总是返回1。要解决此问题,请更改

count++;
return size(currentNode.next);

return 1 + size(currentNode.next);

另外,替换return count;return 1;.

基本上,您的实现几乎是正确的。size(Node)应该返回从该节点开始的列表的大小。如果节点没有 a next,则大小为 1。否则,其当前节点 (1) + 剩余尾部的大小。

您应该制作 2-arg 版本add和 1-arg 版本,size private因为您不想将列表的内部内容公开(事实上,Node该类也应该是私有类)。

此外,您永远不会使用last您班级的字段。您可以删除它,也可以使用它来完全避免在add. 在后一种情况下,您必须在每次添加时正确更新它。

于 2016-12-08T19:30:27.790 回答
0

代替return size(currentNode.next);试试这个return count + size(currentNode.next);

鉴于列表很好,它将解决计数问题。但是一目了然地检查您的代码看起来列表添加代码也有问题。

于 2016-12-08T18:05:15.807 回答