2012-10-24 85 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