206. Reverse Linked List

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

Iteration:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur = head;
        ListNode prev = null;
        while(cur != null){
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
        //  if (head == null || head.next == null) return head;
        // ListNode newHead = reverseList(head.next);
        // head.next.next = head;
        // head.next = null;
        // return newHead;
    }
}

迭代,原理是设置一个prev和cur分别指向前一个和当前的指针,每次都是先要保存当前指的下一个防止丢失。然后每一步都只reverse一个,即cur指向prev,直到最后一个。

递归,每次减小一个

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        // ListNode cur = null;
        // while(head != null){
        //     ListNode next = head.next;
        //     head.next = cur;
        //     cur = head;
        //     head = next;
        // }
        // return cur;
         if (head == null || head.next == null) return head;
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

Recursively 的讲解:https://www.youtube.com/watch?time_continue=1&v=MRe3UsRadKw

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10345468.html