https://leetcode.com/problems/rotate-list/
이렇게 풀면 안된다.. 다시 풀어보자.
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var rotateRight = function(head, k) {
if (!head) return head;
if (!head.next) return head;
let answer = head;
let curr = head;
let count = 0;
while (curr) {
count++;
curr = curr.next;
};
for (let i = 0; i < k % count; i++) {
answer = rotate(answer);
}
return answer;
};
function rotate(node) {
// node를 받으면 순서를 오른쪽으로 옮겨주는 함수.
let newNode = node;
let curr = node;
const newNext = curr;
let count = 0;
while (newNode.next) { // 마지막 노드 찾기
count++;
newNode = newNode.next;
}
count--;
while (count) {
count--;
curr = curr.next;
}
curr.next = null;
newNode.next = newNext;
return newNode;
}
'알고리즘 풀이' 카테고리의 다른 글
[C언어] 1614. Maximum Nesting Depth of the Parentheses (0) | 2024.04.07 |
---|---|
[LeetCode] 416. Partition Equal Subset Sum (0) | 2022.10.09 |
[LeetCode] 71. Simplify Path (0) | 2022.07.17 |
[LeetCode] 푸는중 103. Binary Tree Zigzag Level Order Traversal (0) | 2022.02.03 |
[자료구조] Linked List (연결 리스트) (0) | 2021.06.01 |