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 | 
													Tags
													
											
												
												- DIY
 - 지쿠악스
 - 30mf
 - 메탈퍼즐
 - 누룽지소금빵
 - 우리시대의역설
 - 블라인드박스
 - 가챠
 - 제프딕슨
 - 프라모델
 - 노노그램
 - 맛집
 - 바질토마토뭐시기
 - 미앤아이
 - 지리데칼
 - LeetCode
 - 코딩테스트
 - 롱라이플
 - 발더스모드
 - 건담
 - 눈알빠지겠네
 - 코테
 - 게임
 - 포켓몬
 - 밥무하마드
 - 취미
 - javascript
 - 건담헤드
 - 유루건
 - 발더스게이트
 
													Archives
													
											
												
												- Today
 
- Total
 
.Zzumbong
[leetCode/JS] 1721. Swapping Nodes in a Linked List 본문
문제 설명
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 <= 1050 <= 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로 변환해서 가지고 놀다가 다시 노드로 보내고 싶다.
 
'coding test > leetCode' 카테고리의 다른 글
| [leetCode/JS] 1975. Maximum Matrix Sum (1) | 2022.11.23 | 
|---|---|
| [leetCode/JS] 374. Guess Number Higher or Lower (1) | 2022.11.23 | 
| [leetCode/JS] 1700. Number of Students Unable to Eat Lunch (0) | 2022.11.23 | 
| [leetCode/JS] 3. Longest Substring Without Repeating Characters (1) | 2022.11.23 | 
| [leetCode/JS] 222. Count Complete Tree Nodes (0) | 2022.11.23 | 
			  Comments