Not a quite difficult question. The idea is based on first version of "Remove Duplicates from Sorted List".
Firstly, remove duplicate nodes from list, at the same time, set dplcFlag to be true, which means that duplicate nodes exist now. Next time when a node with different value is met, remove the preNode.
In the following code, preHead is a fake head node before this list, which is very useful when we have cases like "1-1-1-1-2-2-2-3-4".
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
ListNode preNode = head;
ListNode preHead = new ListNode(0);
preHead.next = preNode;
ListNode tmpHead = preHead;
ListNode crntNode = preNode.next;
boolean dplcFlag = false;
while(crntNode !=null){
if(preNode.val == crntNode.val){
preNode.next = crntNode.next;
crntNode.next = null;
crntNode = preNode.next;
dplcFlag = true;
}else{
if(dplcFlag){
tmpHead.next = crntNode;
preNode.next = null;
preNode = crntNode;
crntNode = crntNode.next;
dplcFlag = false;
}
else{
tmpHead = preNode;
preNode = crntNode;
crntNode = crntNode.next;
}
}
}
if(dplcFlag)
tmpHead.next = crntNode;
preNode.next = null;
preNode = crntNode;
}
return preHead.next;
}
}
No comments:
Post a Comment