【2022初春】【LeetCode】83. 删除排序链表中的重复元素

怎么返回链表头还是没写明白

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {       
        ListNode cun = head;       
        if(head==null) return null;
        while(cun.next!=null){
            if(cun.val==cun.next.val){
                cun.next = cun.next.next;
            }else cun = cun.next;
        }
        return head;
    }
}

其实写明白了!问题出在,虚拟头结点默认赋值0的话会出错,因为测试用例刚好是0,所以要初始化成其他值,就没有问题了

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode cunhead = new ListNode(1000);       
        ListNode cun = cunhead;
        cunhead.next = head;       
        if(head==null) return null;
        while(cun.next!=null){
            if(cun.val==cun.next.val){
                cun.next = cun.next.next;
            }else cun = cun.next;
        }
        return cunhead.next;
    }
}
上一篇:tensorflow(三十九):实战——深度残差网络ResNet18


下一篇:算法题,c++,合并K个升序链表,原链表修改链接顺序降低空间复杂度,分治合并降低时间复杂度