1. Title
Given a sorted linked list, delete all duplicate elements so that each element appears only once.
Example 1:
输入: 1->1->2
输出: 1->2
Example 2:
输入: 1->1->2->3->3
输出: 1->2->3
Second, the solution
Specifies the current
pointer to the head head
;
traverse the list, comparison current
and current->next
, if not equal, then current
moves to the next position, and vice versa, then current
the next pointer is current->next
pointing to the next pointer to the next, that is current->next->next
.
Time complexity: O (n), space complexity: O (1).
class ListNode {
public $val = 0;
public $next = null;
function __construct($val) {
$this->val = $val;
}
}
function deleteDuplicates($head) {
$current = $head;
while ($current != null && $current->next != null) {
if ($current->val == $current->next->val) {
$current->next = $current->next->next;
} else {
$current = $current->next;
}
}
return $head;
}