Thursday, October 3, 2013

P3C4: Write a program in C Sharp to implement Linked List for adding, deleting and retrieving data items.

//Source code

using System;

class Subject
{
    public string SubjectName;
    public Subject Next;
}

class ListOfSubjects
{
    private int size;

    public ListOfSubjects()
    {
        size = 0;
        Head = null;
    }
    public int Count
    {
        get { return size; }
    }

    public Subject Head;

    public int Add(Subject NewItem)
    {
        Subject Sample = new Subject();

        Sample = NewItem;
        Sample.Next = Head;
        Head = Sample;
        return size++;
    }

    public Subject Retrieve(int Position)
    {
        Subject Current = Head;

        for (int i = 0; i < Position && Current != null; i++)
            Current = Current.Next;
        return Current;
    }

    public bool Delete()
    {
        if (Head == null)
        {
            Console.WriteLine("The list is empty");
            return false;
        }

        Subject Current;

        Current = Head.Next;
        Head.Next = Current.Next;
        size--;
        return true;
    }

    public bool Delete(int Position)
    {
        if (this.Retrieve(Position) == null)
            return false;

        this.Retrieve(Position - 1).Next = this.Retrieve(Position + 1);
        size--;
        return true;
    }

    public bool Find(Subject ItemToFind)
    {
        Subject Current = new Subject();

        if (ItemToFind == null)
            return false;

        for (Current = Head; Current != null; Current = Current.Next)
        {
            if (Current.SubjectName == ItemToFind.SubjectName)
                return true;
        }

        return false;
    }
}

class Exercise
{
    static int Main()
    {
        ListOfSubjects Subjects = new ListOfSubjects();
        Subject Sub;
        Subject SubjectToFind;

        Sub = new Subject();
        Sub.SubjectName = "Maths";
        Subjects.Add(Sub);

     
        Console.WriteLine(" === Output ===");
        Console.WriteLine("Number of Subjects: {0}", Subjects.Count);

        for (int i = 0; i < Subjects.Count; i++)
        {
            Subject s = Subjects.Retrieve(i);
            Console.WriteLine("\nSubjects Information");
            Console.WriteLine("Subject Name: {0}", Sub.SubjectName);
        }

        SubjectToFind = new Subject();
        SubjectToFind.SubjectName = "Maths";
     

        bool Found = Subjects.Find(SubjectToFind);
        if (Found == true)
            Console.WriteLine("\nItem was found\n");
        else
            Console.WriteLine("\nItem not found\n");

        Console.ReadKey();
        return 0;
    }
}

No comments:

Post a Comment