LeetCode # 83-Remove Duplicates from Sorted List-Remove duplicate elements in sorted list

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 currentpointer to the head head;
traverse the list, comparison currentand current->next, if not equal, then currentmoves to the next position, and vice versa, then currentthe next pointer is current->nextpointing 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;
}

Guess you like

Origin www.cnblogs.com/sunshineliulu/p/12679274.html