力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
public ListNode deleteDuplicates (ListNode head) {
// write code here
//使用指针
if(head == null){
return null;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy.next;
ListNode fast =dummy.next;
fast = fast.next;
while(fast!=null){
if(fast.val==slow.val){ //一定要注意比较的是值
slow.next=fast.next;
fast = fast.next;
}else{
slow = slow.next;
fast = fast.next;
}
}
return dummy.next;
}
进阶:
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
public ListNode deleteDuplicates (ListNode head) {
// write code here
//上一题删选相同的,这一再上一次基础上再次筛选,如果相同,直接删除
//使用指针
if (head == null) {
return null;
}
ListNode dummy = new ListNode(-1); //给链表前加上表头,方便可能的话删除第一个节点
dummy.next = head;
ListNode cur = dummy;
while(cur.next!=null&&cur.next.next!=null){
if(cur.next.val==cur.next.next.val){
int temp = cur.next.val;
//去除所有相同值节点
while(cur.next!=null&&cur.next.val==temp){
cur.next = cur.next.next;
}
}else{
cur = cur.next;
}
}
return dummy.next;
}