清凉世界

喜欢喜欢我的...

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

public class GenericList<T>
{
    private class Node
    {
        // T used in non-generic constructor
        public Node(T t)
        {
            next = null;
            data = t;
        }

        private Node next;
        public Node Next
        {
            get { return next; }
            set { next = value; }
        }

        // T as private member data type
        private T data;

        // T as return type of property
        public T Data
        {
            get { return data; }
            set { data = value; }
        }
    }

    private Node head;

    // constructor
    public GenericList()
    {
        head = null;
    }

    // T as method parameter type:
    public void AddHead(T t)
    {
        Node n = new Node(t);
        n.Next = head;
        head = n;

    }

    public IEnumerator<T> GetEnumerator()
    {
        Node current = head;

        while (current != null)
        {
            yield return current.Data;
            current = current.Next;
        }
    }

}



    注意看黄色字 那一段的意思大家应该都知道 但让人容易晕,它每加一个元素都是 新加的元素的NextNode指象上一个元素. 在看红色的那段 它就把添加完后的最后一个字段当成了头 然后去找它的NextNode,导至跌代出来的结果是反序的.


然后我就想给Node在加一个属性 Head   代码如下


public class MyCollectionTest<T>
{
    private class MyNode
    {
        private T _Date;
        private MyNode _NextNode;
        private MyNode _Head;
        public T Date
        {
            set { _Date = value; }
            get { return _Date; }
        }
        public MyNode NextNode
        {
            set { _NextNode = value; }
            get { return _NextNode; }
        }
        public MyNode Head
        {
            set { _Head = value; }
            get { return _Head; }
        }
       
        public MyNode(T a)
        {          
            Date = a;
            NextNode = null;
            Head = null;
        }
    }

    private MyNode current;

 public MyCollectionTest()
 {
  //
  // TODO: 在此处添加构造函数逻辑
  //      
        current = null;
 }

    public void AddNode(T i)
    {
        MyNode node = new MyNode(i);

        if (current != null)
        {
            current.NextNode = node;
        }
        node.Head = current;
        current = node;

    }

    public IEnumerator<T> GetEnumerator()
    {
        MyNode currentt = current;
        while ((currentt.Head != null)||(current.NextNode!=null))
        {
            yield return currentt.Date;
            currentt = currentt.Head;
        }
    }
}
这里就很奇怪了 当我添加了两个元素
 MyCollectionTest<int> abc = new MyCollectionTest<int>();
        abc.AddNode(1);
        abc.AddNode(2);
        foreach (int i in abc)
        {
            Response.Write(i.ToString());
        }

它总是只显示一条出来.. 蓝色字那段在循环第二次的时候就跳出了While 而我在即时窗口发现currentt.NextNode.Date 是有值的 也就是说current.NextNode!=null 应该是成立的 但它不成立  哪位细心人能帮我看看 我实在是找不出原因了!

posted on 2007-08-24 17:00  清凉tea  阅读(246)  评论(1)    收藏  举报