我想實現簡單的鏈表和添加項目及其看來我Add
功能進入死循環,我不知道爲什麼添加節點到鏈表
public class IntNode
{
private int _value;
private IntNode _next;
public IntNode(int val, IntNode n)
{
_value = val;
_next = n;
}
public int getValue()
{
return _value;
}
public IntNode getNext()
{
return _next;
}
public void setValue(int v)
{
_value = v;
}
public void setNext(IntNode next)
{
_next = next;
}
public string ToString()
{
return _value.ToString();
}
}
public class IntList
{
private IntNode _head;
public static int count;
public IntList()
{
_head = null;
count = 0;
}
public IntList(IntNode node)
{
_head = node;
}
public void Add(IntNode node)
{
if (_head == null)
_head = node;
else
{
for (IntNode p = _head; p.getNext() != null; p.getNext()) { }
_head.setNext(node);
count++;
}
}
public void ToString()
{
IntNode cur = _head;
while (cur.getNext() != null)
{
Console.WriteLine(cur.ToString());
cur = cur.getNext();
}
}
}
主要
static void Main(string[] args)
{
IntList list = new IntList();
list.Add(new IntNode(5, null));
list.Add(new IntNode(2, null));
list.Add(new IntNode(8, null));
list.Add(new IntNode(1, null));
list.ToString();
}
爲什麼不保留對尾部的引用? – zerkms
在'for'循環中是否指'p = p.getNext()'? –
是的,爲什麼?...... – user2908206