[LeetCode] 83. Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
Given
1->1->2
, return 1->2
.Given
1->1->2->3->3
, return 1->2->3
.
Thought process:
Iterate through the list, and check if the value of the next node is the same as this node. There are two cases:
- Value of the next node == value of this node: delete next node.
- Otherwise, increment current node.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode current = head; while (current != null) { if (current.next != null && current.next.val == current.val) { current.next = current.next.next; } else { current = current.next; } } return head; } } |
Time complexity: O(n).
Comments
Post a Comment