coding test/leetCode
[leetCode/JS] 1721. Swapping Nodes in a Linked List
쭘봉
2022. 11. 23. 11:22
문제 설명
You are given the head
of a linked list, and an integer k
.
Return the head of the linked list after swapping the values of the k^th
node from the beginning and the k^th
node from the end (the list is 1-indexed).
입출력 예
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
Example 2:
Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]
Constraints
- The number of nodes in the list is
n
. 1 <= k <= n <= 105
0 <= Node.val <= 100
내 솔루션
k - 1
만큼first
를 진행시킨 후firstNode
에 저장.first
,second
를 남은first
만큼 진행 시킨다.firstNode
에는 k번째 노드가 있고listNode.length - k
번째 노드는second
에 저장된다.- 교환하면 끝.
var swapNodes = function(head, k) {
let first = head;
let second = head;
let firstNode = head;
for(let i = 0; i < k - 1; i++) {
first = first.next;
}
firstNode = first;
while(first.next){
first = first.next;
second = second.next;
}
let temp = firstNode.val;
firstNode.val = second.val;
second.val = temp;
return head;
};
감상평
- linkNode 문제는 항상 귀찮고 까다롭다.
- 차라리 얕은 복사로 array로 변환해서 가지고 놀다가 다시 노드로 보내고 싶다.