Problem
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
Solution (Java)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
ListNode current = head;
ListNode next = current.next;
while (null != next) {
if (current.val == next.val) {
current.next = next.next;
} else {
current = next;
}
next = current.next;
}
return head;
}
}
Solution (Javascript)
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
var now = head;
while (now) {
if (now.next && now.next.val === now.val) {
now.next = now.next.next;
} else {
now = now.next;
}
}
return head;
};
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(1).