LeetCode – Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Thoughts
The key of this problem is using the right loop condition. And change what is necessary in each loop. You can use different iteration conditions like the following 2 solutions.
Solution 1
/** * 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) { if(head == null || head.next == null) return head; ListNode prev = head; ListNode p = head.next; while(p != null){ if(p.val == prev.val){ prev.next = p.next; p = p.next; //no change prev }else{ prev = p; p = p.next; } } return head; } } |
/** * 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) { if(head == null || head.next == null) return head; ListNode prev = head; ListNode p = head.next; while(p != null){ if(p.val == prev.val){ prev.next = p.next; p = p.next; //no change prev }else{ prev = p; p = p.next; } } return head; } }
Solution 2
public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null) return head; ListNode p = head; while( p!= null && p.next != null){ if(p.val == p.next.val){ p.next = p.next.next; }else{ p = p.next; } } return head; } } |
public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null) return head; ListNode p = head; while( p!= null && p.next != null){ if(p.val == p.next.val){ p.next = p.next.next; }else{ p = p.next; } } return head; } }
Related posts:
- LeetCode – Reverse Linked List II (Java)
- LeetCode – Remove Duplicates from Sorted List II (Java)
- LeetCode – Remove Duplicates from Sorted Array II (Java)
- LeetCode – Remove Duplicates from Sorted Array (Java)
Remove duplicates from a sorted linked list
Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once.
For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43->60.