zoukankan      html  css  js  c++  java
  • C#创建单链表,翻转单链表

    直接上代码

    class Program
        {
            static void Main(string[] args)
            {
                int[] src = { 1, 2, 3, 4, 5, 6, 7 };
                Node n = BuildNodeList(src);
                PrintNode(n);
                Node rn = ReverseList(n);
                PrintNode(rn);
                Console.Read();
            }
    
            private static void PrintNode(Node nodeList)
            {
                Node p = nodeList;
                while (p != null)
                {
                    Console.WriteLine(p.Value);
                    p = p.Next;
                }
            }
    
            private static Node BuildNodeList(int[] src)
            {
                if (src == null || src.Length == 0)
                {
                    return null;
                }
                int i = 1;
    
                //创建首链表
                Node root = new Node() { Value = src[0] };
                Node p = root;
                while (i < src.Length)
                {
                    p.Next = new Node() { Value = src[i] };
                    p = p.Next;
                    i++;
                }
                return root;
            }
    
            private static Node ReverseList(Node srcNode)
            {
                Node l = srcNode;
                Node r;
                Node p = srcNode.Next;
    
                //第一个节点的next设置为null
                srcNode.Next = null;
                while(p != null)
                {
                    //保留下一个指针
                    r = p.Next;
    
                    //反转指针
                    p.Next = l;
    
                    //往前走一步
                    l = p;
                    p = r;
                }
                return l;
            }
        }
    
        public class Node
        {
            public Node Next { get; set; }
            public int Value { get; set; }
        }
  • 相关阅读:
    别让猴子翻到背上
    python生成二维码
    50条经典爱情观
    智力测试题
    SQL数据库优化
    递归函数实现二分查找法
    软件开发类别
    递归函数的深度问题
    UVALive
    UVALive
  • 原文地址:https://www.cnblogs.com/xiao123/p/3351486.html
Copyright © 2011-2022 走看看