Last active
August 21, 2016 04:36
-
-
Save wayetan/8130168 to your computer and use it in GitHub Desktop.
Remove Duplicates from Sorted List
This file contains 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. | |
*/ | |
/** | |
* 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) { | |
ListNode curr = head; | |
while(curr != null && curr.next != null){ | |
if(curr.val == curr.next.val) | |
curr.next = curr.next.next; | |
else | |
curr = curr.next; | |
} | |
return head; | |
} | |
} |
This file contains 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 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. | |
*/ | |
public class Solution { | |
public ListNode deleteDuplicates(ListNode head) { | |
ListNode dummy = new ListNode(0); | |
dummy.next = head; | |
// pointer | |
ListNode prev = dummy; | |
ListNode curr = head; | |
while (curr != null){ | |
if (curr.next != null && curr.val == curr.next.val) { | |
int val = curr.val; | |
while(curr != null && curr.val == val) { | |
curr = curr.next; | |
} | |
prev.next = curr; | |
} else { | |
prev = curr; | |
curr = curr.next; | |
} | |
} | |
return dummy.next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment