[刷题] LinkedList - Leetcode - 206 Reverse Linked List

Posted by 西维蜀黍的OJ Blog on 2019-07-17, Last Modified on 2019-07-17

Description

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?

Solution1 - 使用栈

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}

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

        ListNode left = head;
        ListNode right = left.next;
        left.next = null;

        while (right != null) {
            ListNode temp = right.next;
            right.next = left;

            left = right;
            right = temp;

        }

        return left;
    }
}

public class Test {
    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;

        Solution.reverseList(n1);
    }
}

Solution2

/**
 * 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 left = null;
        ListNode right = head;
        while(right != null){
            ListNode tmp = right.next;
            right.next = left;
            
            left = right;
            right = tmp;
        }
        return left;
    }
}

Solution3 - 递归

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