using System;
using System.Diagnostics;
/// </summary>Single linked list.</summary>
public class List<T> {
/// <summary>Each node.</summary>
private class Node {
public T? Value { get; set; }
public Node? Next { get; set; }
}
/// </summary>To run over the list.</summary>
public class ListCursor {
public ListCursor(List<T> owner)
{
this.List = owner;
}
public List<T> List { get; }
public T? Value {
get {
if ( this.Node is null ) {
return default(T);
}
return this.Node.Value;
}
}
private Node? Node { get; set; }
public void Reset() => this.Node = this.List._beg;
public void Next() => this.Node = this.Node?.Next;
public bool IsEnd() => this.Node is null;
}
public List()
{
this._beg = this._end = null;
this.Cursor = new ListCursor( this );
this.Count = 0;
}
public void Add(T x)
{
Debug.Assert( x is not null, "List.Add(): x es null");
Trace.WriteLine( $"List.Add(): {x}" );
Trace.Indent();
var node = new Node { Value = x };
var oldEnd = this._end;
if ( this._beg is null ) {
Trace.WriteLine( "List.Add(): _beg = _end = node" );
this._beg = this._end = node;
} else {
Trace.WriteLine( "List.Add(): _end.Next = node" );
this._end.Next = node;
this._end = node;
}
this.Count++;
this.ChkInvariant();
Debug.Assert( oldEnd != this._end, "List.Add(): there's no new node" );
Trace.Unindent();
}
public int Count { get; private set; }
/// <summary>
/// Class invariant.
/// The list should be traversable at all times.
/// While traversing the list, we should count Count nodes.
/// The last node should be _end.
/// ** This is solely compiled in the Debug profile. **
/// </summary>
[Conditional("DEBUG")]
public void ChkInvariant()
{
Trace.WriteLine( "List.ChkInvariant()" );
var node = this._beg;
Node? prev = null;
int num = 0;
while( node != null ) {
++num;
prev = node;
node = node.Next;
}
Debug.Assert( prev == this._end, "List.ChkInvariant: end is not the end of the list" );
Debug.Assert( num == this.Count, $"Expected {this.Count}, found {num}." );
}
public ListCursor Cursor { get; }
private Node? _beg;
private Node? _end;
}
static class Ppal {
static void Main()
{
Trace.Listeners.Add( new ConsoleTraceListener() );
var l = new List<int>();
for(int i = 0; i < 10; ++i) {
l.Add( i + 1 * 100 );
}
l.Cursor.Reset();
while ( !l.Cursor.IsEnd() ) {
Console.WriteLine( l.Cursor.Value );
l.Cursor.Next();
}
Trace.Close();
}
}