2014-01-14 133 views
0

我想实现简单的链表和添加项目及其看来我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(); 

    } 
+0

为什么不保留对尾部的引用? – zerkms

+1

在'for'循环中是否指'p = p.getNext()'? –

+0

是的,为什么?...... – user2908206

回答

2

问题是for循环中的增量步骤。它需要是p = p.getNext()而不仅仅是p.getNext()。后者只是调用getNext功能,不做任何处理,这意味着p绝不会被修改,因此,循环就不会取得任何进展

for (IntNode p = _head; p.getNext() != null; p = p.getNext()) { } 

下一个问题是你是不是真正的移动_head或使用p返回值。因此,你实际上并没有找到可以插入的地方。你需要的是像下面

IntNode p = _head; 
while (p.getNext() != null) { 
    p = p.getNext(); 
} 
p.setNext(node); 
+0

@zerkms不,编译器必须假定'getNext'具有需要发生的副作用,因此它不会将其删除 – JaredPar

+0

@zerkms这是无关紧要的。代码在第一个地方显然是错误的。 –

+0

@Ondrej Tucny:确实无关紧要,我只是对编译器行为感到好奇 – zerkms

1
for (IntNode p = _head; p.getNext() != null; p.getNext()) { } 

您没有使用p的任何地方,而不是做在循环体中任何东西。你能发现你的问题吗?

0

首先,你没有任何地方分配的getNext()结果:

for (IntNode p = _head; p.getNext() != null; p.getNext()) { } 

其次,你甚至不会在任何地方使用的最后一个节点。事实上,你甚至不能,因为p不会在for循环外存在......

忠告:保持到最后节点的参考以及使您的生活更简单。

0

您的循环永不结束,因为p不会增加。

如果您保留对上次插入项目的引用,应该会更容易些。例如:

private IntNode _lastNode; 

public void Add(IntNode node) 
{ 
    if (_head == null) 
     _head = node; 
    else 
    { 
     if (_lastNode == null) 
      _lastNode = _head; 

     _lastNode.setNext(node) 
     _lastNode = node; 
    } 
    count++; 
} 

每次尝试添加节点时都不必循环访问节点。

+0

只是为了方便:通常将它命名为“tail” – zerkms