/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next ==null) return head;
ListNode dummyhead = new ListNode(-1);
ListNode dummy = dummyhead;
dummy.next = head; //potential unique element
ListNode curr =head.next;
while(curr!=null){
boolean flag = false;
//going into this loop means there are duplicate elements
while(curr!=null && dummy.next.val == curr.val){
flag = true;
curr=curr.next;
}
//loop runs till curr is at a unique element
if(flag){
dummy.next = curr; //changing potential unique element
}
//we already had the right unique potential element
else{
dummy = dummy.next;
}
if(curr!=null)curr = curr.next;
}
return dummyhead.next;
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter