[leetCode]206. 反转链表

双指针

在这里插入图片描述

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode tempNext = cur.next;
            cur.next = prev;
            prev = cur;
            cur = tempNext;
        }
        return prev;
    }
}

递归

class Solution {
    public ListNode reverseList(ListNode head) {
    // 和双指针法初始化是一样的逻辑
        // ListNode* cur = head;
        // ListNode* pre = NULL;
        return reverse(null, head);
    }
    private ListNode reverse(ListNode prev, ListNode cur) {
        if (cur == null) return prev;
        ListNode tempNext = cur.next;
        cur.next = prev;
        // 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步
        // pre = cur;
        // cur = temp;
        return reverse(cur, tempNext);
    }
}
posted @ 2020-10-23 20:50  消灭猕猴桃  阅读(53)  评论(0编辑  收藏  举报