xiao123

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

直接上代码

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; }
    }

 

posted on 2013-10-04 14:34  xiao123  阅读(366)  评论(0编辑  收藏  举报