-2

我正在尝试编写链表并遇到一些问题:

这是 intNode 类:

public class IntNode
{
    private int _value;
    private IntNode _next;

    public IntNode(int v, IntNode n)
    {
        _value = v;
        _next = n;

    }
    public int getValue()
    {
        return _value;
    }

    public IntNode getNext()
    {
        return _next;
    }

    public void setValue(int v)
    {
        _value = v;
    }

    public void setNext(IntNode n)
    {
        _next = n;
    }
}

我的链表类:

public class Set
{
    private IntNode _head;
    private IntNode _current;
    private IntNode _lastNode;

    /**
     * create a new empty Set object
     */
    public Set()
    {
        _head = null;
        _current = null;
        _lastNode = null;
    }

    /**
     * check if the object empty
     * @return true if Set object contain elements, false otherwise
     */
    public bool isEmpty()
    {
        return (_head == null);
    }

    /**
     * add number to Set object
     * @param x - the number to be add 
     */
    public void addToSet(int x)
    {
        if (isEmpty())
        {
            _head = new IntNode(x, _current);
            _head.setNext(_current);
        }
        else
        {
            _current = new IntNode(x, _lastNode);
            _current.setNext(_lastNode);
        }
    }

    /**
     * return a string representation of this Set 
     */
    public String toString()
    {
        String temp = "";

        for (IntNode currentNode = _head; currentNode != null; currentNode.getNext())
        {
            temp += currentNode.getValue() + ",";
        }

        return temp;
    }

我的 addToSet 和 toString 方法有问题,我找不到它。

4

2 回答 2

1

改变:

    /**
     * add number to Set object
     * @param x - the number to be add 
     */
    public void addToSet(int x)
    {
        if (isEmpty())
        {
            _head = new IntNode(x, _current);
            _head.setNext(_current);
        }
        else
        {
            _current = new IntNode(x, _lastNode);
            _current.setNext(_lastNode);
        }
    }

至:

    /**
     * add number to Set object
     * @param x - the number to be add 
     */
    public void addToSet(int x)
    {
        if (isEmpty())
        {
            _head = new IntNode(x, null);
        }
        else
        {
            _current = new IntNode(x, null);
            _lastNode.setNext = _current;
            _lastNode = current;
        }
    }
于 2012-06-17T14:02:14.587 回答
0
for (IntNode currentNode = _head; currentNode != null; currentNode.getNext())
{
   temp += currentNode.getValue() + ",";
}

您的方法中的 for 循环的问题toString()(在旁注中为什么不覆盖ToString()?)是您没有重新分配currentNodecurrentNode.getNext()返回一个您没有使用的对象 - 而是将其重新分配给currentNode

for (IntNode currentNode = _head; currentNode != null; currentNode = currentNode.getNext())
{
   temp += currentNode.getValue() + ",";
}

这段代码看起来更像 Java 而不是 C# - 研究使用属性,遵守命名约定并使用特定于语言的习语。

于 2012-06-17T13:56:42.470 回答