题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
<?php /*class ListNode{ var $val; var $next = NULL; function __construct($x){ $this->val = $x; } }*/ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ function deleteDuplicates( $head ) { if($head == null || $head->next == null){ return $head; } $pre = null; $beg = $head; while($beg != null){ if($pre != null && $beg->val == $pre->val){ // 删除beg $pre->next = $beg->next; $beg = $pre->next; }else{ $pre = $beg; $beg = $beg->next; } } return $head; }
两个指针pre和beg,在pre的值和beg的值相等的时候,删除beg节点,beg指向下一个。