eliminate the duplicates in a sorted linked list (1)

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

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 nodeNode 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 nodeif (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 applicableif (headunchanged == true) {newHead = head;headunchanged = false;}//update the next value in the prev nodeif (prev != null) {prev.next = head;}prev = head;head = head.next;}}return newHead;}
http://blog.csdn.net/beiyeqingteng

原创粉丝点击