这是一道很基本的题目,有Iterative和Recursive两种解法,我们最好都需要熟悉。
- Iterative solution
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { // Initialization ListNode prev = null; ListNode curr = head; while(curr != null){ ListNode next = curr.next; curr.next = prev; prev = curr; curr = next; } // Do not forget to return the new head reference at the end! return prev; } }
- Recursive solution
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { // Base case if(head == null || head.next == null){ return head; } // Keep the new head of the reversed linked list ListNode newHead = reverseList(head.next); head.next.next = head; head.next = null; return newHead; } }