链表处理this
力扣连接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/指针
示例 1:code
输入: 1->1->2排序
输出: 1->2leetcode
示例 2:rem
输入: 1->1->2->3->3it
输出: 1->2->3io
<?php /** * Definition for a singly-linked list. * class ListNode { * public $val = 0; * public $next = null; * function __construct($val) { $this->val = $val; } * } */ class Solution { /** * @param ListNode $head * @return ListNode */ function deleteDuplicates($head) { $pre = $head; while( $pre->next!==null ){ if($pre->val==$pre->next->val){ $pre->next=$pre->next?$pre->next->next:null; }else{ $pre=$pre->next; } } return $head; } }
连接 https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/function
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
<?php /** * Definition for a singly-linked list. * class ListNode { * public $val = 0; * public $next = null; * function __construct($val) { $this->val = $val; } * } */ class Solution { /** * @param ListNode $head * @return ListNode */ function deleteDuplicates($head) { $pre = new ListNode(0); $pre->next = $head; $head=$pre; //新的链表头 while( $pre->next){ $left = $pre->next; //左指针 $right = $left; //右指针 while ($right->next && $right->next->val == $left->val){ $right = $right->next; } if($right == $left){ $pre = $pre->next; }else{ $pre->next = $right->next; } } return $head->next; } }