083-remove-duplicates-from-sorted-list
Question
https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example:
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
Thought Process
- Compare next node
- Link the cur node to next.next if same as current
- Time complexity O(n)
- Space complexity O(1)
Solution
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur = head;
while(cur != null && cur.next != null){
if(cur.val == cur.next.val) cur.next = cur.next.next;
else cur = cur.next;
}
return head;
}
}