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;
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
Wednesday, June 11, 2014
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment