add a node to the beginning of a linked list in csharp

To add a node to the beginning of a linked list in C#, follow these steps:

  1. Create a new node with the data you want to insert.
  2. Set the next pointer of the new node to the current head of the linked list.
  3. Set the head of the linked list to be the new node.

Here's some sample code to accomplish this:

main.cs
public class Node
{
    public int Data;
    public Node Next;
}

public class LinkedList
{
    public Node Head;

    public void InsertAtBeginning(int data)
    {
        Node newNode = new Node();
        newNode.Data = data;

        if (Head == null)
        {
            Head = newNode;
        }
        else
        {
            Node temp = Head;
            Head = newNode;
            newNode.Next = temp;
        }
    }
}
436 chars
28 lines

In the above code, the InsertAtBeginning method is used to insert a new node at the beginning of the linked list. If the linked list is empty (i.e., Head is null), then the new node is simply set as the head of the linked list. Otherwise, the current head of the linked list is stored in a temporary variable temp, the head of the linked list is set to the new node, and the next pointer of the new node is set to temp.

gistlibby LogSnag