package michael.leetcode.linkedlist;

/**
 * Given a sorted linked list, delete all nodes that have duplicate numbers,
 * leaving only distinct numbers from the original list.
 * 
 * For example, Given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3,
 * return 2->3.
 * 
 * @author Michael Wan.
 *
 */
public class RemoveDuplicateFromSortedList2 {
	public ListNode deleteDuplicates(ListNode head) {
		// do make sure to check boundaries.
		if (head == null || head.next == null) {
			return head;
		}
		ListNode result = new ListNode(0);
		ListNode resultHead = result;
		ListNode checkDup = head;
		boolean isRemoveCurrent = false;
		while (head.next != null) {
			if (head.val == head.next.val) {
				head.next = head.next.next;
				isRemoveCurrent = true;
				continue;
			}
			if(!isRemoveCurrent){
				result.next = checkDup;
			}else{
				result.next = head.next;
			}
			result = result.next;
			checkDup = head.next;
			isRemoveCurrent = false;
			head = checkDup;
			
		}

		return resultHead.next;
	}

	public static void main(String[] args) {
		ListNode node1 = new ListNode(1);
		ListNode node2 = (node1.next = new ListNode(1));
		ListNode node3 = (node2.next = new ListNode(2));
		ListNode node4 = (node3.next = new ListNode(3));
		ListNode node5 = (node4.next = new ListNode(6));
		ListNode node6 = (node5.next = new ListNode(6));

		ListNode recorderList = new RemoveDuplicateFromSortedList2()
				.deleteDuplicates(node1);
		printNode(recorderList);

	}

	private static void printNode(ListNode node) {
		while (node != null) {
			System.out.print(String.format("%s->", node.val));
			node = node.next;
		}
	}
}

@@ -733,21 +733,16 @@
 %09%09%09%09head
-.next
  = head.
@@ -745,21 +745,16 @@
 ead.next
-.next
 ;%0D%0A%09%09%09%09i
@@ -803,16 +803,17 @@
 %7D%0D%0A%09%09%09if
+ 
 (!isRemo
@@ -822,16 +822,17 @@
 Current)
+ 
 %7B%0D%0A%09%09%09%09r
@@ -862,43 +862,285 @@
 %0A%09%09%09
-%7Delse%7B%0D%0A%09%09%09%09result.next = head.next
+%09checkDup = checkDup.next;%0D%0A%0D%0A%09%09%09%09// when 2 duplicate element in the end of the list, make sure%0D%0A%09%09%09%09// the previous element not append them.%0D%0A%09%09%09%09result.next.next = null;%0D%0A%09%09%09%7D else %7B%0D%0A%09%09%09%09checkDup = head.next;%0D%0A%09%09%09%09isRemoveCurrent = false;%0D%0A%09%09%09%09head = checkDup;%0D%0A%09%09%09%09continue
 ;%0D%0A%09
@@ -1144,16 +1144,18 @@
 %0D%0A%09%09%09%7D%0D%0A
+%0D%0A
 %09%09%09resul
@@ -1176,34 +1176,8 @@
 t;%0D%0A
-%09%09%09checkDup = head.next;%0D%0A
 %09%09%09i
@@ -1222,19 +1222,16 @@
 ckDup;%0D%0A
-%09%09%09
 %0D%0A%09%09%7D%0D%0A%0D
@@ -1231,16 +1231,138 @@
 %0A%09%09%7D%0D%0A%0D%0A
+%09%09// remember to check last element after loop, for linked list.%0D%0A%09%09if (!isRemoveCurrent) %7B%0D%0A%09%09%09result.next = head;%0D%0A%09%09%7D%0D%0A
 %09%09return

remove duplicate in sorted list II.