从链表中删除最后一个节点c#

Remove last node from linked list c#

我将元素添加到 Stack 并在 DataGridView 中打印它们。它工作正常。但我无法删除最后一个元素。你能帮我看看我的方法吗?

这是我搜索最后一个节点的方式:

public void RemoveLast()
        {

            STACKnode current = head, last;
            while (current != null)
            {
                last = current;
                current = current.next;
            }
            last = null;
        }

但是 last = null 不会删除节点。但是,如果我尝试更改值 last.item,它将被更改。

我的链表完整代码:

public class STACKnode
    {
        public STACKnode next;
        public int item;
    }

    public class LinkedList
    {
        private STACKnode head;
        public int currentItem;

        public void AddLast(int item)
        {
            if (head == null)
            {
                head = new STACKnode();

                head.item = item;
                head.next = null;
            }
            else
            {
                STACKnode newSTACKnode = new STACKnode();
                newSTACKnode.item = item;
                STACKnode current = head;
                while (current.next != null)
                {
                    current = current.next;
                }

                current.next = newSTACKnode;
            }
        }
        public void RemoveLast()
        {

            STACKnode current = head, last;
            while (current != null)
            {
                last = current;
                current = current.next;
            }
            last = null;
        }
        public void printAllNodes(DataGridView dataGridView1)
        {
            STACKnode current = head;
            int i = 0;
            dataGridView1.RowCount = 1;
            while (current != null)
            {
                dataGridView1.Rows.Add("" + current.item);
                current = current.next;
                i = i + 1;
            }
        }}

对不起我的英语不好

通过将 null 分配给 last,您只是在更改此变量的值。您应该做的是更改它之前节点的 "next" 属性,这样它们之间的 link 就会中断,从而有效地删除最后一项。这应该有效:

public void RemoveLast()
    {
        STACKnode current = head, last;

        if (head == null) return;
        if (head.next == null){
            head = null;
            return;
        }

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

编辑:添加了一个空列表和一个节点列表的案例。