admin管理员组

文章数量:1596266

Question:

Given a sorted list, and remove the duplicates in the list. For example, 1 -> 2 -> 2 -> 3, after removing the duplicates, we have  1 -> 2  -> 3

Analyze:

when we remove the duplicates, we consider all the duplicates as a composite node, and we remove the duplicates from the composite node and update the "next" value of the first node in the composite node.

Code:

public static Node removeDuplication(Node head) {
	if (head == null || head.next == null ) return head;
	Node listHead = head; 
	
	while (head != null) {
		// if true, we will remove the nodes in the composite node
		// and only keep the first node in the composite node
		if (head.next != null && head.value == head.next.value) {
			// the head of the composite node
			Node headComposite = head;
			while (head.next != null && head.value == head.next.value) {
				head = head.next;
			}
			//head is the first node in the next composite node
			head = head.next;
			//update the next value
			headComposite.next = head;
		} else {
			head = head.next;
		}
	}
	return listHead;		
}
转载请注明出处:http://blog.csdn/beiyeqingteng

本文标签: DuplicatesEliminateListsorted