Reader Level:
ARTICLE

Insertion at the begining of a Linklist in C#

Posted by Abhishek Bhandari Articles | C# Language July 11, 2009
This code snippet shows how to insert data to a Linklist at the beginning.
  • 0
  • 0
  • 5442

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication38
{
    class node
    {
        public int delete;
        public int data;/*it will store the data*/
        public node link;/*it will hold the address of the next memory location where the data is stored*/
    }
    class Program
    {
        /*these are the variables */
        public static node START;
        public static node LASt;
        public static node CURRENT;
        public Program()
        {
            START = null;
            LASt = null;
        }
        public void insertionbegin()
        {
            node newnode = new node();
            Console.WriteLine("Enter the data");
            newnode.data = int.Parse(Console.ReadLine());
            newnode.link = START;
            START = newnode;
            Console.WriteLine("DAta has been inserted");

        }

        public void displaynode()
        {
            Console.WriteLine("Data in the list are");
            CURRENT = START;
            while (CURRENT != null)
            {
                Console.WriteLine(CURRENT.data);
                CURRENT = CURRENT.link;
            }
            Console.ReadLine();

        }

        static void Main(string[] args)

        {
            Program obj = new Program();
            do
            {
                Console.Clear();
                Console.WriteLine("********************************************");
                Console.WriteLine("**        MAIN MENU     *****************");
                Console.WriteLine("**************************************");
                Console.WriteLine("*1.Inserting at the end of the list******");
                Console.WriteLine("*2.Insertion at the begining of the list****");
                Console.WriteLine("*3.Display the list       *******************");
                Console.WriteLine("*4.Exit                      ****************");
                Console.WriteLine("*********************************************");
                Console.WriteLine("\nEnter ur choice");
                int choice = int.Parse(Console.ReadLine());
                switch (choice)
                {
                    case 1: { break; }
                    case 2: { obj.insertionbegin(); break; }
                    case 3: { obj.displaynode(); break; }
                    case 4: { break; }
                    default: { Console.WriteLine("Invalid option"); break; }
                }
            } while (true);
            Console.ReadLine();

        }
    }
}

COMMENT USING

Trending up