【问题标题】:Pop from stack(LinkedList) using C# doesnt update Stack使用 C# 从堆栈(链表)弹出不更新堆栈
【发布时间】:2012-10-14 02:26:36
【问题描述】:

您好,我正在使用 C# 并尝试从 MainWindow 调用函数 Pop(Node 类)。 pop 方法应该返回弹出的值并将其从堆栈中删除。该函数正在运行,并且从函数中删除了最高值,但在 MainWindow 中,堆栈看起来相同(LinkedList 没有改变)。这是我的 Node 类和 Pop 函数。

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

在主窗口中,我正在创建堆栈并调用 Pop。 但堆栈看起来相同 - CustID 为 1->2->3->4->5 而不是 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 

/

谢谢, 克里希纳

【问题讨论】:

    标签: data-structures linked-list stack


    【解决方案1】:

    我认为您的主要问题是您解决此问题的方法。您正在尝试以 C 方式编写堆栈并将 C# 对象视为 C 指针。

    在 pop() 函数中,temp = null; 行只会将变量 temp 设置为 null 值,并且stackTop 仍将具有非空值。您应该知道,将变量设置为 null 并不是释放对象的正确方法。

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

    问候

    【讨论】:

      猜你喜欢
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      • 2014-12-18
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      相关资源
      最近更新 更多