Sha256: 3bcf26df3a141cb895734145fe4cd542b903d45076a843a3c80bbb12d4e6a10f

Contents?: true

Size: 1.2 KB

Versions: 396

Compression:

Stored size: 1.2 KB

Contents

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class SimpleLinkedList<T> : IEnumerable<T>
{
    public SimpleLinkedList(T value) :
        this(new[] { value })
    {
    }

    public SimpleLinkedList(IEnumerable<T> values)
    {
        var array = values.ToArray();

        if (array.Length == 0)
        {
            throw new ArgumentException("Cannot create tree from empty list");
        }

        Value = array[0];
        Next = null;

        foreach (var value in array.Skip(1))
        {
            Add(value);
        }
    }

    public T Value { get; }

    public SimpleLinkedList<T> Next { get; private set; }

    public SimpleLinkedList<T> Add(T value)
    {
        var last = this;

        while (last.Next != null)
        {
            last = last.Next;
        }

        last.Next = new SimpleLinkedList<T>(value);

        return this;
    }

    public IEnumerator<T> GetEnumerator()
    {
        yield return Value;

        foreach (var next in Next?.AsEnumerable() ?? Enumerable.Empty<T>())
        {
            yield return next;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.179 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.178 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.177 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.176 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.175 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.174 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.173 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.172 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.171 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.170 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.169 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.167 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.166 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.165 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.164 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.163 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.162 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.161 tracks/csharp/exercises/simple-linked-list/Example.cs
trackler-2.2.1.160 tracks/csharp/exercises/simple-linked-list/Example.cs