Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 우리시대의역설
- LeetCode
- 제프딕슨
- 포켓몬
- 게임
- 지리데칼
- 프라모델
- 유루건
- 발더스모드
- 밥무하마드
- 누룽지소금빵
- 미앤아이
- 30mf
- 노노그램
- 블라인드박스
- 코테
- 건담헤드
- javascript
- 취미
- 발더스게이트
- 지쿠악스
- 바질토마토뭐시기
- 건담
- 맛집
- 메탈퍼즐
- 눈알빠지겠네
- DIY
- 코딩테스트
- 롱라이플
- 가챠
Archives
- Today
- Total
.Zzumbong
[leetCode/JS] 328. Odd Even Linked List 본문
난이도 [ 🤔 ] Medium
문제 설명
Given the head
of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
The first node is considered odd, and the second node is even, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in O(1)
extra space complexity and O(n)
time complexity.
짝수는 링크드 링크드리스트는 뒤로 보낸다.
입출력 예
Example 1:
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
Example 2:
Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
Constraints
- The number of nodes in the linked list is in the range
[0, 104]
. -106 <= Node.val <= 106
내 솔루션
- 자세한 사항은 console.log()를 보며 차근차근 따라해보자.
/**
* @param {ListNode} head
* @return {ListNode}
*/
function oddEvenList(head) {
if (!head) return head;
var odd = head;
var even = head.next;
while (odd.next && odd.next.next) {
var tmp = odd.next;
// 1
odd.next = odd.next.next;
// 2
odd = odd.next;
// 3
tmp.next = odd.next;
// 4
}
odd.next = even;
console.log(head)
return head;
}
// { head: [1,2,3,4,5], odd: [1,2,3,4,5], even: [2,3,4,5] }
// 1 { odd: [1,2,3,4,5], even: [2,3,4,5], tmp: [2,3,4,5] }
// 2 { odd: [1,3,4,5], even: [2,3,4,5], tmp: [2,3,4,5] }
// 3 { odd: [3,4,5], even: [2,3,4,5], tmp: [2,3,4,5] }
// 4 { odd: [3,4,5], even: [2,4,5], tmp: [2,4,5] }
// 1 { odd: [3,4,5], even: [2,4,5], tmp: [4,5] }
// 2 { odd: [3,5], even: [2,4,5], tmp: [4,5] }
// 3 { odd: [5], even: [2,4,5], tmp: [4,5] }
// 4 { odd: [5], even: [2,4], tmp: [4] }
// [1,3,5,2,4]
감상평
- 링스드 리스트는 참 어렵다. 주소 참조에 대해서도 알고 주시하고 있어야한다. 귀찮.
'coding test > leetCode' 카테고리의 다른 글
[leetCode/JS] 872. Leaf-Similar Trees (0) | 2022.12.08 |
---|---|
[leetCode/JS] 938. Range Sum of BST (0) | 2022.12.07 |
[leetCode/JS] 876. Middle of the Linked List (0) | 2022.12.05 |
[leetCode/JS] 2256. Minimum Average Difference (0) | 2022.12.04 |
[leetCode/JS] 451. Sort Characters By Frequency (2) | 2022.12.03 |
Comments