在链接列表实现中的特定节点之后添加新节点

时间:2018-04-26 07:34:38

标签: c# linked-list

我正在关注一些教程在C#中实现链表。这是我从该教程中复制的代码。

 internal class Node
    {
        internal int data;
        internal Node next;
        public Node(int d)
        {
            data = d;
            next = null;
        }
    }
    internal class SingleLinkedList
    {
        public void printAllNodes()
        {
            Node current = head;
            while (current != null)
            {
                Console.WriteLine(current.data);
                current = current.next;
            }
        }
        internal Node head;
        internal void InsertFront(SingleLinkedList singlyList, int new_data)
        {
            Node new_node = new Node(new_data);
            new_node.next = singlyList.head;
            singlyList.head = new_node;
        }
        internal void InsertLast(SingleLinkedList singlyList, int new_data)
        {
            Node new_node = new Node(new_data);
            if (singlyList.head == null)
            {
                singlyList.head = new_node;
                return;
            }
            Node lastNode = GetLastNode(singlyList);
            lastNode.next = new_node;
        }
        internal Node GetLastNode(SingleLinkedList singlyList)
        {
            Node temp = singlyList.head;
            while (temp.next != null)
            {
                temp = temp.next;
            }
            return temp;
        }
        internal void InsertAfter(Node prev_node, int new_data)
        {
            if (prev_node == null)
            {
                Console.WriteLine("The given previous node Cannot be null");
                return;
            }
            Node new_node = new Node(new_data);
            new_node.next = prev_node.next;
            prev_node.next = new_node;
        }
    }
}

现在我添加了一些节点并显示它正常工作。

SingleLinkedList obj = new SingleLinkedList();
            obj.InsertFront(obj, 7);
            obj.printAllNodes();
            obj.InsertFront(obj, 9);
            obj.printAllNodes();
            obj.InsertLast(obj, 345);
            obj.printAllNodes();

现在我想用#34; InsertAfter"我正在使用的功能但它工作不正常,它仍然显示旧的节点。它有什么问题?

obj.InsertAfter(new Node(7), 10);
            obj.printAllNodes();

1 个答案:

答案 0 :(得分:1)

也许这是你的要求:

SingleLinkedList obj = new SingleLinkedList();
obj.InsertFront(obj, 7);
obj.InsertFront(obj, 9);
var d = obj.GetLastNode(obj);
obj.InsertLast(obj, 345);
obj.InsertAfter(d, 44);
obj.printAllNodes();

如果你不改变课程SingleLinkedList,我认为这是最好的解决方案。但如果我是你,我会考虑编辑那个课程。

修改

我会实现"插入"像这样的方法:

internal Node InsertFront(SingleLinkedList singlyList, int new_data)
{
    Node new_node = new Node(new_data);
    new_node.next = singlyList.head;
    singlyList.head = new_node;
    return new_node;
}

因此,我不会调用obj.InsertFront(obj, 7);而是调用Node node = obj.InsertFront(obj, 7);,然后它会帮助我在任何节点之后插入节点:obj.InsertAfter(node, 44);