merge-nodes-between-zeroes.dart (1258B)
1 //Merge the values contained between zeroes and return the new linked list. 2 //Ex. 0 1 2 0 2 2 2 2 0 3 //Output [3, 8] 4 //Explanation: Adding 1 and 2 between the first two zeroes gives us 3 5 //then adding 2 4 times gives eight. 6 //The time complexity of this code is O(n) where n is the number 7 //of nodes in the inputted list. 8 //Time: 569ms Beats: 50% 9 //Memory: 229.9MB Beats: 16.67% 10 11 12 /** 13 * Definition for singly-linked list. 14 * class ListNode { 15 * int val; 16 * ListNode? next; 17 * ListNode([this.val = 0, this.next]); 18 * } 19 */ 20 class Solution { 21 ListNode? mergeNodes(ListNode? head) { 22 23 ListNode? start; 24 ListNode? last; 25 head = head?.next; 26 int total = 0; 27 while(head != null){ 28 if(head.val == 0){ 29 if(start == null){ 30 start = new ListNode(); 31 start.val = total; 32 total = 0; 33 last = start; 34 } 35 else{ 36 ListNode current = new ListNode(); 37 current.val = total; 38 last?.next = current; 39 last = current; 40 total = 0; 41 } 42 } 43 total += head.val; 44 head = head.next; 45 } 46 return start; 47 } 48 }