206. Reverse Linked List

题目:

Reverse a singly linked list.

链接: http://leetcode.com/problems/reverse-linked-list/

题解:

反转单链表,必须做得非常熟练。这个method将会是许多复杂题目的一个组成部分。

Time Complexity - O(n), Space Complexity - O(1)

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

二刷:

就是做一个fakehead,然后在head != null的情况下进行翻转。

Java:

Time Complexity - O(n), Space Complexity - O(1)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode dummy = new ListNode(-1);
        ListNode tmp = dummy;
        while (head != null) {
            tmp = head.next;
            head.next = dummy.next;
            dummy.next = head;
            head = tmp;
        }
        return dummy.next;
    }
}

Reursive:

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

三刷:

ListNode tmp的定义放在循环里其实也就是创建一个reference,这个reference只是为了寻址,在32位机器上是32-bits,在64位机器上是64-bits,但有的JVM可以支持在64位机器上使用32位的bit。所以我们放在循环外的话可以重复使用。否则假如这个链表的长度为,我们在循环内每次都创建新reference的话,要使用len - 1个reference。

Java:

Time Complexity - O(n), Space Complexity - O(1)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode dummy = new ListNode(-1);
     ListNode tmp = null;
while (head != null) { tmp = head.next; // reference to head.next head.next = dummy.next; dummy.next = head; head = tmp; } return dummy.next; } }

Reference:

https://leetcode.com/discuss/34474/in-place-iterative-and-recursive-java-solution

https://leetcode.com/discuss/40956/my-java-recursive-solution

原文地址:https://www.cnblogs.com/yrbbest/p/4493546.html