Leetcode - Reverse Linked List

Leetcode - Reverse Linked List_第1张图片

My code:

/**
 * 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;
        // /** iterative */
        // ListNode pre = head;
        // ListNode curr = head.next;
        // while (curr != null) {
        //     ListNode temp = curr.next;
        //     curr.next = pre;
        //     pre = curr;
        //     curr = temp;
        // }
        // head.next = null;
        // return pre;
        /** recursive */
        ListNode tail = head;
        while (tail.next != null)
            tail = tail.next;
        reverse(head);
        return tail;
    }
    
    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode pre = reverse(head.next);
        pre.next = head;
        head.next = null;
        return head;
    }
}

这道题目用两种方法实现了反转链表。
一种是直接遍历,一边遍历一边反转。
一种是,用递归实现反转。

Anyway, Good luck, Richardo!

你可能感兴趣的:(Leetcode - Reverse Linked List)