How to remove the first node from linear (single) (singly) linked list in C#

1 Answer

0 votes
using System;

namespace ConsoleApplication1
{
    public class Node
    {
        public Node Next;
        public object Data;
    }
    public class LinkedList
    {
        private Node head;
        private Node current;
        public int Count;

        public LinkedList()
        {
            head = new Node();
            current = head;
        }
        public void AddToLast(object data)
        {
            Node newNode = new Node();
            newNode.Data = data;
            current.Next = newNode;
            current = newNode;
            Count++;
        }
        public void AddToStart(object _data)
        {
            Node newNode = new Node() { Data = _data };
            newNode.Next = head.Next;
            head.Next = newNode;
            Count++;
        }
        public void RemoveFromStart()
        {
            if (Count > 0)
            {
                head.Next = head.Next.Next;
                Count--;
            }
        }
        public void PrintAllNodes()
        {
            Console.Write("Head->");
            Node curr = head;
            while (curr.Next != null)
            {
                curr = curr.Next;
                Console.Write(curr.Data);
                Console.Write("->");
            }
            Console.WriteLine("NULL");
        }
        static void Main(string[] args)
        {
            LinkedList llist = new LinkedList();

            llist.PrintAllNodes();
  
            llist.AddToLast("c#");
            llist.PrintAllNodes();

            llist.AddToLast("Java");
            llist.AddToLast(100);
            llist.PrintAllNodes();

            llist.AddToStart("JavaScript");
            llist.AddToStart(300);
            llist.AddToStart("C++");
            llist.PrintAllNodes();

            Console.WriteLine("Total Nodes: {0}\n", llist.Count);

            llist.RemoveFromStart();
            llist.RemoveFromStart();
            llist.PrintAllNodes();

            Console.WriteLine("Total Nodes: {0}", llist.Count);
        }
    }
}

/*
run:
   
Head->NULL
Head->c#->NULL
Head->c#->Java->100->NULL
Head->C++->300->JavaScript->c#->Java->100->NULL
Total Nodes: 6

Head->JavaScript->c#->Java->100->NULL
Total Nodes: 4
      
*/

 



answered Apr 22, 2017 by avibootz
...