Merge Nodes in Between Zeros
给一个linkedlist, 里面的数字由0分割, 求0之间的数字的和的list.
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 |
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode mergeNodes(ListNode head) { ListNode resDummy = new ListNode(); ListNode res = resDummy; int tmp = 0; while(head != null && head.next != null){ if(head.next.val == 0){ res.next = new ListNode(tmp); res = res.next; tmp = 0; }else { tmp += head.next.val; } head = head.next; } return resDummy.next; } } |