刪除排序鏈表中的重複元素

鏈表處理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;
    }
}
相關文章
相關標籤/搜索