Implement a linked list that supports the IEnumerable interface - CSharp Collection

CSharp examples for Collection:IEnumerable

Description

Implement a linked list that supports the IEnumerable interface

Demo Code

using System;//www. java 2s  .  c  o m
using System.Collections;
public class _node {
   public _node    next;
   public _node    prev;
   public object   value;
   public _node( ) { next = prev = null; value = null; }
   public _node( object o ) {
      value = o;
      next = prev = null;
   }
   public _node( _node n ) {
      next = n.next;
      prev = n.prev;
      value = n.value;
   }
}
public class LinkedListEnumerator : IEnumerator {
   private _node m_current = null;
   private _node m_begin   = null;
   public LinkedListEnumerator( _node n ) { m_current = m_begin = n; }
   //Implement the IEnumerator interface
   public object Current {
      get { return m_current.value; }
      set { m_current.value = value; }
   }
   public bool MoveNext( ) {
      m_current = m_current.next;
      return m_current == null ? false : true;
   }
   public void Reset( ) {
      m_current = m_begin;
   }
}
public class LinkedList : IEnumerable {
   private _node   m_root = null;
   //Implement the IEnumerable interface method GetEnumerator( )
   public IEnumerator GetEnumerator( ) {
      return (IEnumerator)new LinkedListEnumerator( m_root.prev );
   }
   //Implement some basic methods
   public void AddHead( object o ) {
      _node n = new _node(o);
      if( m_root == null )
         m_root = n;
      else {
         n.next = m_root;
         n.prev = m_root.prev;
         m_root.prev.next = n;
         m_root.next.prev = n;
         m_root = n;
      }
   }
}
public class LinkedListTest {
   public static void Main( ) {
      LinkedList l = new LinkedList( );
      for(int i = 0; i < 10; i++ )
         l.AddHead( i );
      foreach( int i in l )
         Console.WriteLine( i );
      }
}

Result


Related Tutorials