알고리즘 풀이
[LeetCode] 61. Rotate List
르라나
2022. 7. 17. 11:47
https://leetcode.com/problems/rotate-list/
Rotate List - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
이렇게 풀면 안된다.. 다시 풀어보자.
/**
* 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;
}