Link: https://leetcode.com/problems/reverse-linked-list/node
The number of nodes in the list is the range [0, 5000]. -5000 <= Node.val <= 5000
Using a dummy head could make things easier.
For each node in the list:
Set node as dummy's successer
Set dummy's successor to this nodeide
class Solution { public ListNode reverseList(ListNode head) { ListNode dummy = new ListNode(0); ListNode cur = head; while (cur != null) { ListNode next = cur.next; cur.next = dummy.next; dummy.next = cur; cur = next; } return dummy.next; } }
class Solution { public ListNode reverseList(ListNode head) { ListNode dummy = new ListNode(0); reverse(head, dummy); return dummy.next; } private void reverse(ListNode head, ListNode dummy) { if (head == null) { return; } ListNode next = head.next; head.next = dummy.next; dummy.next = head; reverse(next, dummy); } }
Similar question:
https://leetcode.com/problems/reverse-linked-list-ii/this