我正在尝试编写链表并遇到一些问题:
这是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方法有问题,我找不到它。
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
for (IntNode currentNode = _head; currentNode != null; currentNode.getNext())
{
temp += currentNode.getValue() + ",";
}
您的toString()
方法中的for循环问题(旁边注意为什么不覆盖ToString()
?)是您没有重新分配currentNode
:{{1返回您未使用的新对象 - 而是将其重新分配给currentNode.getNext()
:
currentNode
此代码看起来更像Java而不是C# - 查看使用属性,观察命名约定并使用特定于语言的习语。