Blind 75
Reverse Linked List
- Problem
- LC 206
- Category
- Linked List
- File
- blind75_LC206ReverseLinkedList.java
- Path
- pkg5leetcode/blind75/blind75_LC206ReverseLinkedList.java
- Package
- pkg5leetcode.blind75
- Command
- java pkg5leetcode/blind75/blind75_LC206ReverseLinkedList.java
- Lesson
- Back to the chapter
- Approach
- Iterative three-pointer reversal.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.blind75;2 3/*4 * Reverse Linked List | LC 2065 * APPROACH: Iterative three-pointer reversal.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class blind75_LC206ReverseLinkedList {9 /** Same shape as pkg5leetcode/common/ListNode.java (nested for single-file runs). */10 11 static class ListNode {12 int val;13 ListNode next;14 ListNode(int val) { this.val = val; }15 }16 17 static ListNode reverseList(ListNode head) {18 ListNode prev = null, cur = head;19 while (cur != null) {20 ListNode nxt = cur.next;21 cur.next = prev;22 prev = cur;23 cur = nxt;24 }25 return prev;26 }27 28 static int[] toArray(ListNode head) {29 java.util.List<Integer> list = new java.util.ArrayList<>();30 while (head != null) { list.add(head.val); head = head.next; }31 return list.stream().mapToInt(Integer::intValue).toArray();32 }33 34 public static void main(String[] args) {35 ListNode a = new ListNode(1); a.next = new ListNode(2); a.next.next = new ListNode(3);36 check(java.util.Arrays.equals(toArray(reverseList(a)), new int[]{3, 2, 1}), "case1");37 ListNode b = new ListNode(1);38 check(java.util.Arrays.equals(toArray(reverseList(b)), new int[]{1}), "case2");39 System.out.println("all tests passed");40 }41 42 static void check(boolean cond, String name) {43 if (!cond) throw new AssertionError("FAILED: " + name);44 System.out.println(" PASS " + name);45 }46}