Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlespunk/7407795 to your computer and use it in GitHub Desktop.
Save charlespunk/7407795 to your computer and use it in GitHub Desktop.
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == null) return null;
ListNode result = null;
ListNode begin = null;
while(head != null){
int num = head.val;
if(head.next != null && head.next.val == num){
while(head != null && head.val == num) head = head.next;
}
else{
if(result == null){
result = head;
begin = result;
}
else{
result.next = head;
result = result.next;
}
head = head.next;
result.next = null;
}
}
return begin;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment