C#反转链表

public class ReverseLinkedList
    {
        void main()
        {
            Node list = InitList();
            Console.WriteLine(list);
            list = list.ReverseList(list);
            Console.WriteLine(list);
        }
        public Node InitList()
        {
            Node head = new Node();
            head.Next = null;
            head.Data = -1;
            Node q, p;
            p = head;
            for (int i = 1; i <= 10; i++)
            {
                q = new Node();
                q.Data = i;
                q.Next = null;
                p.Next = q;
                p = q;
            }
            return head;
        }
    }
    public class Node
    {
        private T data;
        private Node next;
        public T Data
        {
            get { return data; }
            set { this.data = value; }
        }
        public Node Next
        {
            get { return next; }
            set { next = value; }
        }
        public Node ReverseList(Node head)
        {
            if (head.Next == null || head.Next.Next == null)
            {
                return head;   /*链表为空或只有一个元素则直接返回*/
            }
            Node t = null,
                     p = head.Next,
                     q = head.Next.Next;
            while (q != null)
            {
                t = q.Next;
                q.Next = p;
                p = q;
                q = t;
            }
            /*此时q指向原始链表最后一个元素,也是逆转后的链表的表头元素*/
            head.Next.Next = null;  /*设置链表尾*/
            head.Next = p;           /*调整链表头*/
            return head;
        }
        public override string ToString()
        {
            string result = string.Empty ;
            Node p = this.Next;
            while (p != null)
            {
                result += string.Format("{0}t", p.Data);
                p = p.Next;
            }
            return result;
        }
    }

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注