代码中有详细注释,直接看代码:
public static ListNode deleteDuplicates(ListNode head) {
//定义虚拟头结点
ListNode dummyHead = new ListNode(-1);
//指向头结点
dummyHead.next = head;
//如果链表等于空或者只有一个元素,直接返回链表
if(head == null || head.next == null) return head;
//定义标记sign,指向头结点下一个结点
ListNode sign = head.next;
//如果不相等的话,让head.next指向sign,然后让head指向sign,sign指向sign下一个结点
//如果head.data == sign.data ,让sign指向sign下一个结点
while(sign != null) {
if(head.data != sign.data) {
head.next = sign;
head = sign;
}
sign = sign.next;
}
//让head的下一个结点指向空座位结束
head.next = null;
return dummyHead.next;
}