Question

I have an assignment to implement a linear linked list using generics in C# console application.

The class should also contain a print() method to print the elements of the list. Conditions for Linear List are to be as a long type (CNodeLong) or String Type (CNodeString), both inherited from CNode with virtual function Print().

I have a problem implementing the printing method. I don't know where should it stand, and how to override it.

Here is my CNode class and CList class:

public class CNode<T>
{
    private CNode<T> next;
    private T item;

    public CNode<T> Next
    {
        get { return next; }
        set { next = value; }
    }

    public T Item
    {
        get { return item; }
        set { item = value; }
    }

     public CNode(T item)
        : this(item,null)
    {
    }

    public CNode(T item, CNode<T> next)
    {
        this.item = item;
        this.next = next;
    }
}

class CList<T>
{
    private CNode<T> first;
    private CNode<T> last;
    private int count;

    public CNode<T> First
    {
        get { return first; }
    }

    public CNode<T> Last
    {
        get { return last; }
    }

    public int Count
    {
        get { return count; }
    }

     public CList(string strListName)
    {
        count = 0;
        first = last = null;
    }
}
Was it helpful?

Solution

You probably should override ToString method and add the virtual Print method to CNode. (I've also added the PrintList method to CList):

public class CNode<T>
{
    ...

    public override string ToString()
    {
        return item.ToString();
    }
    virtual public void Print()
    {
        Console.WriteLine(item);
    }   
}

class CList<T>
{
    ...

    public void PrintList()
    {
        CNode<T> current = first;
        while (current != null)
        {
            Console.WriteLine(current.ToString());
            current = current.Next;
        }
    }
}

Then you can override the virtual method in the child classes:

public class CNodeString : CNode<string>
{
    public CNodeString(string item) : base(item) { }

    override public void Print()
    {
        Console.WriteLine("Printing from CNodeString");
        base.Print();
    }
}

public class CNodeLong : CNode<long>
{
    public CNodeLong(long item) : base(item) { }

    override public void Print()
    {
        Console.WriteLine("Printing from CNodeLong");
        base.Print();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top