|
| 1 | +- 문제 : https://leetcode.com/problems/reorder-list/ |
| 2 | +- 블로그 링크 : https://algorithm.jonghoonpark.com/2024/06/10/leetcode-143 |
| 3 | + |
| 4 | +## 방법 1 (list 사용) |
| 5 | + |
| 6 | +- time complexity : O(n) |
| 7 | +- space complexity : O(n) |
| 8 | + |
| 9 | +```java |
| 10 | +class Solution { |
| 11 | + public void reorderList(ListNode head) { |
| 12 | + List<ListNode> list = new ArrayList<>(); |
| 13 | + |
| 14 | + ListNode current = head; |
| 15 | + while (current.next != null) { |
| 16 | + list.add(current); |
| 17 | + current = current.next; |
| 18 | + } |
| 19 | + list.add(current); |
| 20 | + |
| 21 | + ListNode reordered = head; |
| 22 | + for (int i = 1; i < list.size(); i++) { |
| 23 | + if (i % 2 == 0) { |
| 24 | + reordered.next = list.get(i / 2); |
| 25 | + } else { |
| 26 | + reordered.next = list.get(list.size() - ((i / 2) + 1)); |
| 27 | + } |
| 28 | + reordered = reordered.next; |
| 29 | + } |
| 30 | + reordered.next = null; |
| 31 | + } |
| 32 | +} |
| 33 | +``` |
| 34 | + |
| 35 | +## 방법 2 (pointer 사용) |
| 36 | + |
| 37 | +- time complexity : O(n) |
| 38 | +- space complexity : O(1) |
| 39 | + |
| 40 | +```java |
| 41 | +class Solution { |
| 42 | + public void reorderList(ListNode head) { |
| 43 | + ListNode prev = null; |
| 44 | + ListNode slow = head; |
| 45 | + ListNode fast = head; |
| 46 | + |
| 47 | + while(slow != null && fast != null && fast.next != null) { |
| 48 | + prev = slow; |
| 49 | + slow = slow.next; |
| 50 | + fast = fast.next.next; |
| 51 | + } |
| 52 | + |
| 53 | + if (prev == null) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + prev.next = null; |
| 58 | + |
| 59 | + ListNode current = head; |
| 60 | + ListNode reversed = reverse(slow); |
| 61 | + while(true) { |
| 62 | + ListNode temp = current.next; |
| 63 | + |
| 64 | + if (reversed != null) { |
| 65 | + current.next = reversed; |
| 66 | + reversed = reversed.next; |
| 67 | + current = current.next; |
| 68 | + } |
| 69 | + |
| 70 | + if (temp != null) { |
| 71 | + current.next = temp; |
| 72 | + current = current.next; |
| 73 | + } else { |
| 74 | + current.next = reversed; |
| 75 | + break; |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + public ListNode reverse(ListNode treeNode) { |
| 81 | + ListNode current = treeNode; |
| 82 | + ListNode prev = null; |
| 83 | + while(current != null) { |
| 84 | + ListNode temp = current.next; |
| 85 | + current.next = prev; |
| 86 | + prev = current; |
| 87 | + current = temp; |
| 88 | + } |
| 89 | + return prev; |
| 90 | + } |
| 91 | +} |
| 92 | +``` |
0 commit comments