鏈表處理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; } }