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 ListNode removeDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = new ListNode(-1);
ListNode preNode = newHead;
while(head != null) {
if (head.next != null && head.val == head.next.val) {
while (head.next != null && head.val == head.next.val) {
head = head.next;
}
head = head.next;
} else {
preNode.next = head;
head = head.next;
preNode = preNode.next;
preNode.next = null;
}
}
return newHead.next;
}
2670

被折叠的 条评论
为什么被折叠?



