zoukankan      html  css  js  c++  java
  • 单链表的思考

    我首先用list实现一个单链表

     class nodes
        {
            private string value;
            private nodes node;
            string result = "";
            public nodes(string value):this(value,null)
            {
                this.value = value;
            }
    
            public nodes(string value,nodes node)
            {
                this.value = value;
                this.node = node;
            }
    
            public override string ToString()
            {
                return value.ToString()+(node==null?"":node.ToString());
            }
          
        }
    
     static void Main(string[] args)
            {
                //单链表
             nodes n1 = new nodes("1");
                nodes n2 = new nodes("2", n1);
                nodes n3 = new nodes("3", n2);
    
                Console.WriteLine(n3);
                Console.ReadKey();
            }
    
    结果:321 ok
    当然我们也可以用范型!将Node改为Node<T>即可, nodes n1 = new nodes("1");也改为 nodes<char> n1 = new nodes<char>("1");

      现在的问题是:上面的代码我只能传同一种类型的值,要是我想传不同类型的值改怎么办呢!

       显然我们可以通过 ,private object value;将所有输入的值都设成object类型。

    这种方法可以,但是难免会带来不断的装箱和拆箱!

    internal class baseNode
        {
            protected baseNode bNode;
            public baseNode(baseNode bNode)
            {
               this.bNode = bNode;
            }
        }
    
        class childNode<T>:baseNode
        {
            T value;
            
            public childNode(T value):this(value,null){}
    
            public childNode(T value,baseNode bnode): base(bnode)
            {
                this.value = value;
            }
    
            public override string ToString()
            {
                return value + ( bNode== null ? "" : bNode.ToString());
            }
        
        }
    
    两种实现方法:
               //单链表
                childNode<string> n1 = new childNode<string>("1");
                childNode<string> n2 = new childNode<string>("2", n1);
                childNode<int> n3 = new childNode<int>(3, n2);
     
                baseNode head = new childNode<string>("1");
                head = new childNode<string>("2",head);
                head = new childNode<int>(3,head);
     
                Console.WriteLine(n3);
                Console.WriteLine(head);

      

  • 相关阅读:
    哈夫曼
    P1631序列合并
    PAT Mice and Rice
    ybt 1356 计算(calc)
    P2947 Look Up S
    electron主进程与渲染进程的通信方式
    自定义BufferedReader
    小程序云数据库查询数据用在其它任意地方(完美解决)
    html+js实现微信跳转遮罩层
    Java创建属于自己的二维码(完整版)
  • 原文地址:https://www.cnblogs.com/fjsnail/p/3254220.html
Copyright © 2011-2022 走看看