2013-07-27 135 views
0

我写了一段代码来实现一个链表,并在一个位置添加一个新节点。为什么插入功能不工作?

public class Node 
{ 
    //this is the class which creates each node. 
    public Node NextInstance; //this is the instance which creates the node. 
    public object data; // this will have the data 
    public Node(object data) //Constructer 
    { 
     this.data = data; 
    } 
    public Node() 
    { 
    } 
} 

public class LinkedList 
{ 
    Node Head; // this is for the head instance. 
    Node Current; 
    Node temp1; 
    // Add the method which will create a node 
    public void Add_Node(Node N) 
    { 
     if (Head == null) 
     { 
      //if the head is null, set the first instance to head 
      Head = N; // "First" = Head 
      Current = Head; // Set the Current to Head; Current = "First" 
     } 
     else 
     { 
      Current.NextInstance = N; // Current.NextInstance = "Second"; 
      Current = Current.NextInstance; //Current = "Second"; 
     } 
    } 
    public void Print_Nodes() 
    { 
     //this is the method to print the instance 
     temp1 = Head; 
     while (Head != null) 
     { 
      //just traverse 
      Console.WriteLine(Head.data); 
      Head = Head.NextInstance; 
     } 
    } 
    public void Insert_Node(int position, string Val) 
    { 
     Node T = new Node(Val); 
     Node temp; 
     //T.data = Val; 
     int k = 0; 
     Head = temp1; 
     while (Head != null) 
     { 
      k += 1; 
      if (k == position) 
      { 
       temp = Head; 
       Head = T; 
       Head.NextInstance = temp; 
      } 
      Head = Head.NextInstance; 
     } 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     LinkedList LL = new LinkedList(); 
     LL.Add_Node(new Node("First")); 
     LL.Add_Node(new Node("Second")); 
     LL.Add_Node(new Node("Third")); 
     //LL.Print_Nodes(); 
     LL.Insert_Node(2, "Shef"); 
     LL.Print_Nodes(); 
     Console.ReadLine(); 
    } 
} 

Insert_Node的代码无法正常工作。任何人都可以纠正我吗?

+0

为什么当框架提供一个时需要实现自己? –

+4

在Insert_Mode方法中,“Head = temp1”行非常值得怀疑:除非position = 0,否则不应更改头部 –

+1

您得到什么错误?为什么不使用内置的'LinkedList '类? – sharoz

回答

0

如果新节点不是头部,则不应更改头节点。

 public void Insert_Node(int position, string Val) 
    { 
     Node T = new Node(Val); 
     Node temp = Head; 
     int i = 0; 
     if (position == i) 
     { 
      T.NextInstance = Head; 
      Head = T; 
     } 
     else 
     { 
      while (temp != null && i < position-1) 
      { 
       temp = temp.NextInstance; 
       i++; 
      } 
      T.NextInstance = temp.NextInstance; 
      temp.NextInstance = T; 
     } 

    } 
相关问题