Home > database >  C# singly linked list sum method
C# singly linked list sum method

Time:08-16

I want to find the sum of a simple list. But I can't create a method Sum() without arguments. Please suggest possible solutions.

void Main()
{
    var chain1 = new Add(5)).Append(new Add(10)).Append(new add(15));
    var sum = chain.Sum();
}

public abstract class Strategy
{
    private Strategy _next;
    public Strategy Append(Strategy next)
    {
        if(_next == null){
            _next = next;
        } else {
            _next.Append(next);
        }
        
        return this;
    }
}

public class Add : Strategy
{
    int _num;
    public Add(int num) => _num = num;
    
    public int Sum()
    {
      ....
    }
}

CodePudding user response:

@marsze is correct, there are much better ways of doing this... but I was able to modify it a bit and ended up with this non battle hardened code:

public abstract class Strategy
{
    protected Strategy _next;

    public Strategy Append(Strategy next)
    {
        if (_next == null)
        {
            _next = next;
        }
        else
        {
            _next.Append(next);
        }

        return this;
    }

    public abstract int Sum();
}

public class Add : Strategy
{
    int _num;
    public Add(int num) => _num = num;

    public override int Sum()
    {
        if (_next == null)
        {
            return _num;
        }

        return _num   _next.Sum();
    }
}

CodePudding user response:

@mxmissile's solution works, but it's not really good coding style. I assume he wanted to stay as close to your example as possible. If this is really a coding exercise though, I assume you want to learn.

So, here is an improved version, with the same behavior basically, but cleaner naming and implementation:

public sealed class NumberChain
{
    private ChainItem _first;
    private ChainItem _last;

    private sealed class ChainItem
    {
        public int Value { get; }
        public ChainItem Next { get; set; }
      
        public ChainItem(int value)
        {
            this.Value = value;
        }
    }
    
    public NumberChain Append(int value)
    {
        var item = new ChainItem(value);
        if (_first == null)
        {
            _first = item;
        }
        if (_last != null)
        {
            _last.Next = item;
        }
        _last = item;
        return this;
    }

    public int Sum()
    {
        var item = _first;
        var sum = 0;
        while (item != null)
        {
            sum  = item.Value;
            item = item.Next;
        }
        return sum;
    }
}

Usage:

var chain = new NumberChain().Append(5).Append(10).Append(15);
var sum = chain.Sum();
  •  Tags:  
  • c#
  • Related