HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
👻
개발 기록
/
코딩테스트 스터디
코딩테스트 스터디
/
Merge Nodes in Between Zeros

Merge Nodes in Between Zeros

Link
https://leetcode.com/problems/merge-nodes-in-between-zeros/
Deadline
Apr 16, 2022
Status
Archived
Type
linked list
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0.
For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's.
Return the head of the modified linked list.
notion image
Constraints:
  • The number of nodes in the list is in the range [3, 2 * 105].
  • 0 <= Node.val <= 1000
  • There are no two consecutive nodes with Node.val == 0.
  • The beginning and end of the linked list have Node.val == 0.
 

풀이

재영짱짱1234
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ var mergeNodes = function(head) { let cacheHead = head; // 맨처음부터 0 0 0 4 5 -> 4 5 부터 시작하도록 while (!cacheHead.val) { cacheHead = cacheHead.next } let prevCacheNode; // 이전의 노드를 캐시. // merge node - 0일 때 -> 연결해주고 + 다음에 숫자가 오는 노드를 캐시 while (head) { if (!head.val) { if (prevCacheNode) { prevCacheNode.next = head.next; // 연결의 의미 } prevCacheNode = head.next; // 다음 캐시된 노드를 설정함. head.next - 숫자가 올 때까지 설정해야 함. head = head.next; continue; } if (head.next) { prevCacheNode.val += head.next.val; .// 이전 캐시 노드는 val !== 0 -> + } head = head.next; } return cacheHead; };
은찬
var mergeNodes = function(head) { const answer = new ListNode(); const arr =[]; let current = head; let sum = 0; while(current !== null){ if(current.val !== 0){ sum += current.val; } else{ if(sum !== 0){ arr.push(sum); sum = 0; } } current = current.next; } current = answer; for(let i = 0; i < arr.length; i++){ current.val = arr[i]; if(i < arr.length - 1){ current.next = new ListNode(); current = current.next; } } return answer; };
효성님을 위해 미리 만들어놓았습니다ㅋㅋㅋ
(감사합니다 ㅋㅋ)
var mergeNodes = function(head) { const mockHead = new ListNode(); let mergedNode = mockHead; let cur = head; while(cur) { if(cur.val === 0 && cur.next) { mergedNode.next = new ListNode(); mergedNode = mergedNode.next; } mergedNode.val += cur.val; cur = cur.next; } return mockHead.next; };