eliminate the duplicates in the sorted list (2)

来源:互联网 发布:软件开发书籍推荐 编辑:程序博客网 时间:2024/06/06 16:49

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 nodeif (head.next != null && head.value == head.next.value) {// the head of the composite nodeNode headComposite = head;while (head.next != null && head.value == head.next.value) {head = head.next;}//head is the first node in the next composite nodehead = head.next;//update the next valueheadComposite.next = head;} else {head = head.next;}}return listHead;}
转载请注明出处:http://blog.csdn.net/beiyeqingteng

原创粉丝点击