Skip to content

Instantly share code, notes, and snippets.

@daifu
Created March 1, 2013 02:48
Show Gist options
  • Select an option

  • Save daifu/5062122 to your computer and use it in GitHub Desktop.

Select an option

Save daifu/5062122 to your computer and use it in GitHub Desktop.
Given a sorted linked list, delete all duplicates such that each element appear only once.
/**
* Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->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) {
// Start typing your Java solution below
// DO NOT write main() function
if (head == null) return null;
ListNode cur = head;
ListNode ahead;
while(cur.next != null) {
ahead = cur.next;
if(ahead.val == cur.val) {
ahead = ahead.next;
cur.next = ahead;
} else {
cur = ahead;
}
}
return head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment