LeetCode206. 反转链表

方法1:迭代反转链表。

☆☆☆方法2:递归反转链表。

class Solution {
//    ListNode pre = null, next = null; // 方法3全局变量
    public ListNode reverseList(ListNode head) {
        /**
         *  方法1:迭代法。 时间复杂度O(n), 空间复杂度O(1)
         */
        if (head == null || head.next == null) return head;
        ListNode cur = head;
        ListNode pre = null, next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
        /**
         *  方法2:递归法。 时间复杂度O(n), 空间复杂度O(n)
         */
        /*
        // 递归终止条件
        if (head == null || head.next == null) {
            return head;
        }
        // cur始终是最后一个节点
        ListNode cur = reverseList(head.next);
        // 如果链表是 1->2->3->4->5,那么此时的cur就是5
        // 而head是4,head的下一个是5,下下一个是空
        // 所以head.next.next 就是5->4
        head.next.next = head;
        // 防止链表循环,需要将head.next设置为空  也就是以前4->5的指针清空
        head.next = null;
        // 每层递归函数都返回cur,也就是最后一个节点
        return cur;
        */
        /**
         *  方法3:将方法1的循环改成递归
         */
        /*
        if (head == null){
            return pre;
        }
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
        return reverseList(head);
        */
    }
}

递归法参考:

  动画演示+多种解法 206. 反转链表

原文地址:https://www.cnblogs.com/HuangYJ/p/14127982.html