83. Remove Duplicates from Sorted List

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val = 0, $next = null) {
 *         $this->val = $val;
 *         $this->next = $next;
 *     }
 * }
 */
class Solution {

    /**
     * @param ListNode $head
     * @return ListNode
     */
    function deleteDuplicates($head) {
        $prev = $head;
        while($prev->next !== null) {
            // skip duplicates item
            if ($prev->val == $prev->next->val) {
                $prev->next = $prev->next->next;
            } 
            // next item
            else {
                $prev = $prev->next;
            }
        }

        return $head;
    }
}

Last updated