Skip to content

Instantly share code, notes, and snippets.

@WeAthFoLD
Created April 16, 2017 15:33
Show Gist options
  • Save WeAthFoLD/3b48163f0738192d9041b52cb6d2b4a8 to your computer and use it in GitHub Desktop.
Save WeAthFoLD/3b48163f0738192d9041b52cb6d2b4a8 to your computer and use it in GitHub Desktop.
Remove Duplicates from Sorted List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
/*
1 2 3 3 3 4 !=
^ ^
1 2 3 3 3 4 !=
^ ^
1 2 3 3 3 4 ==
^ ^
1 2 3 3 3 4 ==
^ ^
1 2 3 3 3 4 !=
^ ^
*/
if (head == null)
return null;
ListNode last = head, cur = head.next;
while (cur != null) {
if (cur.val == last.val) {
cur = cur.next;
} else {
last.next = cur;
last = cur;
cur = cur.next;
}
}
last.next = null;
return head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment