206. 反转链表

221 阅读1分钟

题目描述

方法一:递归

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

方法二:迭代

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;//这里注意,如果一开始pre=head,cur = head.next 会有环
        ListNode cur = head;
        while (cur != null) {
            ListNode tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
        
    }
}