@Test public void Test1() { ListNode node11 = new ListNode(1); ListNode node21 = new ListNode(2); ListNode actual = solution.mergeTwoLists(node11, node21); ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); node1.next = node2; ListNode expect = node1; assertTrue(ListNode.isSameList(actual, expect)); }
public ListNode deleteDuplicates(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; // last unique node we found ListNode node = pre.next; while (node != null) { // find the last node that has the same value as current node while (node.next != null && node.next.val == node.val) { node = node.next; } // now, node has different value from its next node (if next // node exists), we need to compare with previous node to // see whether `node` has unique value if (pre.next == node) { // ! don't use (pre.val == node.val) unless you are sure // dummy has different value from head node pre = node; } else { pre.next = node.next; } node = node.next; } return dummy.next; }