怎么返回链表头还是没写明白
/**
* 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;
}
}