admin管理员组

文章数量:1596328

Qustion:

Given a sorted linked list, and remove all the nodes which have duplication. For example, 1 -> 1 -> 2 -> 2 -> 3 ->4 , after removing duplicates, the linked list becomes 3 ->4.

Analyze:

1. In order to remove the duplicated nodes in the list, we consider the duplicates as a composite node. After removing the composite node, we need to make sure that  remaining nodes are still connected. Therefore, we need to have a pointer which points to the parent node of the composite node. When the composite node is removed, the parent node will point to the next non-duplicated node.

2. If the first node belongs to a composite node, we need to return a new head.

Code:

public static Node removeDuplication(Node head) {
	if (head == null || head.next == null ) return head;
	//father node
	Node prev = null;
	Node newHead = null;
	//if the newhead has been determined,
	//we will not change the head any more.
	boolean headunchanged = true;
	
	while (head != null) {
		// if true, we will remove the composite node
		if (head.next != null && head.value == head.next.value) {
			while (head.next != null && head.value == head.next.value) {
				head = head.next;
			}
			head = head.next;
			if (head == null && prev != null) {
				prev.next = null;
			}
			
		} else {
			//change head if applicable
			if (headunchanged == true) {
				newHead = head;
				headunchanged = false;
			}
			//update the next value in the prev node
			if (prev != null) {
				prev.next = head;
			}
			prev = head;
			head = head.next;
		}
	}
	return newHead;		
}
http://blog.csdn/beiyeqing teng

本文标签: DuplicatesEliminatesortedListLinked