2012-12-03 75 views
0

我正在链接列表..我成功插入和删除节点在第一个节点..但是当我尝试插入节点在最后..它给出了一个错误“对象引用未设置到对象”插入最后节点单链表

我的逻辑是正确的,但Visual Studio是产生一个异常不知道为什么 请帮我出的实例..下面

class MyList 
{ 
    private Node first; 
    private Node current; 
    private Node previous; 

    public MyList() 
    { 
     first = null; 
     current = null; 
     previous = null; 
    } 

    public void InsertLast(int data) 
    { 
     Node newNode = new Node(data); 

     current = first; 

     while (current != null) 
     { 
      previous = current; 
      current = current.next; 
     } 

     previous.next = newNode; 
     newNode.next = null; 
    } 

    public void displayList() 
    { 
     Console.WriteLine("List (First --> Last): "); 
     Node current = first; 
     while (current != null) 
     { 
      current.DisplayNode(); 
      current = current.next; 
     } 
     Console.WriteLine(" "); 
    } 
} 



class Node 
{ 
    public int info; 
    public Node next; 

    public Node(int a) 
    { 
     info = a; 
    } 

    public void DisplayNode() 
    { 
     Console.WriteLine(info); 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     MyList newList = new MyList(); 

     newList.InsertLast(10); 
     newList.InsertLast(20); 
     newList.InsertLast(30); 
     newList.InsertLast(40); 

     newList.displayList(); 

     Console.ReadLine(); 
    } 
} 
+1

“我的逻辑是正确的,但视觉工作室正在产生一个异常” - 不,你的逻辑是错误的,你的代码导致异常 - 不要责怪你的工具! – tomfanning

回答

0

如果

完整的代码给出列表是空的,首先会等于空和哟当您尝试执行此操作时,您的代码会引发异常previous.next = newNode;,因为previous也是null。将第一个节点时,您必须将新元素添加为第一,所以改写这样的代码:

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

      while (current != null) 
      { 
       previous = current; 
       current = current.next; 
      } 
      previous.next = newNode; 
     } 
     newNode.next = null; 
} 

编辑:可以实现它是这样的,但照顾,如果拳头为空和只有第一个节点的情况。检查方法:

public void RemoveLast() 
{    
     if (first != null)//there is no point in removing since the list is empty 
     { 
      if (first.next == null) //situation where list contains only one node 
       first = null; 
      else //all other situations 
      { 
       current = first; 

       while (current.next != null) 
       { 
        previous = current; 
        current = current.next; 
       } 
       previous.next = null; 
      } 
     } 
} 
+0

是啊,它的工作原理...谢谢aloot ...请你给我一个想法如何从最后删除节点? –

+0

检查编辑的答案。希望它有帮助 –

+0

它可以帮助我alooot ...谢谢aloot ...上帝保佑你 –

2

基本上,你将不得不处理一个空列表的情况。在当前的代码中,当列表为空时,您的前一个,当前和第一个全部等于null。所以你得到一个错误,因为当前一个等于null时你试图分配一个值​​。