題目概要
給訂一個 head 鏈結串列,head 以 0 開頭。兩個 0 中間合併為一段,並計算其總和,最後輸出整個鏈結串列合併後總和的結果。
![[JavaScript] LeetCode 2181. Merge Nodes in Between Zeros KNjQbXr KNjQbXr [JavaScript] LeetCode 2181. Merge Nodes in Between Zeros](https://i.imgur.com/KNjQbXr.png)
解題技巧
- LeetCode 已經幫忙實現了 ListNode,所以我們只需要去判斷當前的值是否為 0,如果為 0 就將和上一個 0 之間的數總和存進一個鏈結串列中;如果不為 0 就將當前的值加進總和並繼續往下判斷。
程式碼
/** * 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 cur = new ListNode(); let dummy = cur; let temp = head; let sum = 0; // 計算連續兩個 0 之間的數的總和 while(temp) { if (temp.val === 0) { // 將到下一個 0 之前的總和存進 cur 中 if (sum !== 0) { cur.next = new ListNode(sum); cur = cur.next; sum = 0; } } else { sum += temp.val; } temp = temp.next } return dummy.next; // 一定會有一個 0, 所以跳過 0 };
![[JavaScript] LeetCode 2181. Merge Nodes in Between Zeros LaU99Ij LaU99Ij [JavaScript] LeetCode 2181. Merge Nodes in Between Zeros](https://i.imgur.com/LaU99Ij.png)
Latest posts by pluto (see all)
- Express + MongoDB 實作使用者增刪改查 API 及登入 API - 2022 年 7 月 2 日
- 解決 React Highcharts 資料筆數過多造成圖表渲染卡頓的情形 - 2022 年 6 月 28 日
- React 那些好看、有趣、實用的函式庫、組件庫推薦(2) - 2022 年 6 月 26 日