Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution:
Method 1: recursively
The idea is to reverse the list from the second node, and attaches the head to the end.
For example:
1 -> 2 -> 3 -> 4
=> 1, 2 -> 3-> 4
=> 2 -> 3 -> 4 -> 1
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; } ListNode reverse = reverseList(head.next); ListNode curr = reverse; while (curr.next != null) { curr = curr.next; } curr.next = head; head.next = null; return reverse; } }
Method 2: iteratively
When we check a node, we want to set its next pointer to its previous node.
Therefore we use a prev node to record its previous node when we go through the list.
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; } ListNode prev = null; while (head != null) { ListNode next = head.next; head.next = prev; prev = head; head = next; } return prev; } }