-
[linked list] reverse linked listAlgorithm/LeetCode 2025. 4. 20. 10:45
✅ Problem
https://leetcode.com/problems/reverse-linked-list/description/
✅ Approach & Solution
방식1) iterative
더보기- 현재 노드의 next가 이전 노드여야 한다.
/** * 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) { ListNode prev = null, current = head; while (current != null) { ListNode next = current.next; current.next = prev; prev = current; current = next; } return prev; } }
방식2) recursive
더보기/** * 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) { return reverse(head, null); } public ListNode reverse(ListNode node, ListNode prev) { if (node == null) { return prev; } ListNode next = node.next; node.next = prev; return reverse(next, node); } }
'Algorithm > LeetCode' 카테고리의 다른 글
[linked list] swap nodes in pairs (0) 2025.05.04 [linked list] add two numbers (0) 2025.04.20 [hash] jewels and stones (0) 2025.04.08 [array] best time to buy and sell stock 2 (0) 2025.04.07 [array] maximum product subarray (0) 2025.04.06