206. Reverse Linked List(Java)

注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注

Reverse a singly linked list.

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

代码1:recursive solution

public class Solution {
    public ListNode reverseList(ListNode head) {
        return reverseListInt(head, null);
    }
    private ListNode reverseListInt(ListNode head, ListNode newNext) {
        if (head == null) 
            return newNext;
        ListNode oldNext = head.next;
        head.next = newNext;
        return reverseListInt(oldNext, head);
    }
}

代码2:iterative solution

public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode newNext = null;
        while (head != null) {
            ListNode oldNext = head.next;
            head.next = newNext;
            newNext = head;
            head = oldNext;
        }
        return newNext;
    }
}

你可能感兴趣的:(leetcode)