2012-10-24 86 views
0

您好我正在使用C#并尝试从MainWindow调用Pop(Node类)函数。 pop方法应该返回poped值并将其从堆栈中移除。该函数正在工作,并且从函数内删除了最高值,但在MainWindow中,堆栈看起来相同(LinkedList不会更改)。这是我的Node类和Pop功能。从堆栈(LinkedList)使用C#弹出不更新堆栈

public class Node 
    { 
     #region Constructor and Declarations 
     public int custId;   
     public Node next; 
     //other fields 

public Node(int _data, Node _next) 
     { 
      this.custId = _data; 
      if (_next != null) 
       this.next = _next; 
      else 
       this.next = null; 
     } 
     public Node() 
     { 
     } 
     #endregion 

//Make Stack 
public Node MakeList() 
     { 

      Node slist1 = new Node(1, null); 
      Node slist2 = new Node(2, null); 
      Node slist3 = new Node(3, null); 
      Node slist4 = new Node(4, null); 
      Node slist5 = new Node(5, null); 

      slist1.next = slist2; 
      slist2.next = slist3; 
      slist3.next = slist4; 
      slist4.next = slist5; 

      return slist1; 
     } 

#region PopCustomer 
public int pop(Node stacktop) 
     { 
      Node temp; 
      int removedCustId = 0; 
      if (stacktop == null) 
       return -1; 

      else 
      { 
       temp = stacktop; 
       removedCustId = temp.custId; 
       stacktop = temp.next; 
       temp = null; 
      } 
      return removedCustId; 
     } 
#endregion 

在mainWindow中,我创建堆栈并调用Pop。 BUT STACK LOOKS SAME - 与CustIDs 1-> 2-> 3-> 4-> 5 NOT 2-> 3-> 4-> 5

//MAIN WINDOW 
     #region MainWindow 
        Node stackTop = new Node(); 
        stackTop=stackTop.MakeList(); 
        int popedItem = stackTop.pop(stackTop);//STACK LOOKS SAME - with CustIDs 1->2->3->4->5 
        #endregion 

/

谢谢, 克里希纳

回答

0

我认为你的主要问题是你的方法对这个问题。您试图以C方式编写堆栈并将C#对象视为C指针。

在弹出()函数,线temp = null;将只设置可变temp作为null值,和stackTop仍将具有非空值。您应该知道将变量设置为null不是释放对象的正确方法。

在C#中默认情况下处于安全模式,不允许指针。我鼓励你阅读关于Generics的文章,这是在C#中实现数据结构的常用方法,您将看到使用动态数组的示例。

Regards