其他分享
首页 > 其他分享> > 【2022初春】【LeetCode】83. 删除排序链表中的重复元素

【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;
    }
}

标签:head,ListNode,val,int,next,链表,2022,cun,83
来源: https://blog.csdn.net/mdzz_z/article/details/122766499