Created
October 23, 2013 02:56
-
-
Save charlespunk/7111896 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
// Note: The Solution object is instantiated only once and is reused by each test case. | |
if(head == null) return null; | |
ListNode left = head; | |
int val = left.val; | |
ListNode right = head.next; | |
while(right != null){ | |
if(right.val == val) right = right.next; | |
else{ | |
left.next = right; | |
left = right; | |
val = left.val; | |
right = right.next; | |
} | |
} | |
left.next = right; | |
return head; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment