public Node merge(Node head) { if (head == null || head.next == null) { return head; } Node newHead = merge(head.next); if (head.val == newHead.val) { head.counter = head.counter + newHead.counter; head.next = newHead.next; } return head; }
public static void main(String[] args) { ListNodeWithCounter test = new ListNodeWithCounter(); Node head = new Node(1, 1); head.next = new Node(1, 3); head.next.next = new Node(4, 2); head.next.next.next = new Node(3, 1); head.next.next.next.next = new Node(3, 1); Node node = test.merge(head); while (node != null) { System.out.print(node.val + ", " + node.counter + "->"); node = node.next; } }