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; }
    }
原文地址:https://www.cnblogs.com/xiao123/p/3351486.html