206. 反转链表

思路

可以使用递归或者迭代方法,注意使用递归的时候,不要管下一层是怎么做的,只要假设当前已经做完就可以了。
迭代需要注意的是,头结点的next要置空

代码

递归

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        //p为子节点的头结点(子结点已经全部翻转完)
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
}

迭代

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode cur = head;
        ListNode pre = null;
        ListNode newHead = null;
        while(cur != null){
            //保存下一个结点,防止翻转连接的时候弄丢
            ListNode nextP = cur.next;
            if(nextP == null){//cur为最后一个结点,那么新链表头结点为cur
                newHead = cur;
            }
            cur.next = pre;//翻转连接
            pre = cur;//pre指针前进
            cur = nextP;//cur指针前进
        }
        return newHead;
    }
}
原文地址:https://www.cnblogs.com/realzhaijiayu/p/13388619.html