Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to insert item at start (front) in 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 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}", llist.Count);
        }
    }
}

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

 



answered Apr 22, 2017 by avibootz
...