C# - Deleting a node from a linked-list by a node, quetion about deleting the first node

daowdos 296 Reputation points
2021-10-27T13:13:43.297+00:00

I have an issue to understanding this -
Why when deleting the first node from a linked-list, by copying the second node on the first node - (the "head" which copied to node by Node node = doubList.head, as I did below, won't be copied by reference)
and thus won't delete the first node and keeps it ?

            NewLinkList newList = new NewLinkList();

            Node first = new Node();
            first.data = 1;
            first.prev = null;
            first.next = null;
            newList.head = first;

            Node second = new Node();
            second.data = 20;
            second.next = null;
            second.prev = first;
            first.next = second;

            Node third = new Node();
            third.data = 27;
            third.next = null;
            third.prev = second;
            second.next = third;

            clearNode(newList, first);
        }

  public class Node
        {
            public int data;
            public Node prev;
            public Node next;
        }
        public class NewLinkList
        {
            public Node head;
            public NewLinkList()
            {
                head = null;
            }
        }
    public static void deleteNode(NewLinkList doubList, Node temp)
    {
        Node node = doubList.head;
        while (node != null)
        {
            if (node == temp)
            {

                if (node.prev == null)
                {
                    doubList.head = node.next;
                    doubList.head.prev = null;
                    //node = node.next;
                    //node.prev = null;
                }
                else
                {
                    node.prev.next = node.next;

                    if (node.next != null)
                    {
                        node.next.prev = node.prev;
                    }
                }
                break;
            }
            node = node.next;
        }
        var temporary = doubList.head;
        do
        {
            Console.WriteLine(temporary.data.ToString());
            temporary = temporary.next;
        }
        while (temporary != null);
    }

Thanks in advance.

Developer technologies .NET .NET CLI
Developer technologies C#
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.