题目描述:
我的解答,我维持了一个快慢指针
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null){
return head;
}else {
ListNode slow=head;
ListNode fast=head.next;
while (fast!=null){
if(slow.val!=fast.val){
slow.next=fast;
slow=slow.next;
}
fast=fast.next;
}
slow.next=null;
}
return head;
}
}
慢指针一开始指向head,快指针指向head.next。当快指针和慢指针的元素不同时,慢指针的next指向快指针。最后的时候慢指针的next指向null。
官方思路:
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return head;
}
ListNode cur = head;
while (cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}
当cur.val和cur.next.val相同时,跳过cur.next,cur.next=cur.next.next.直到遇到不等的时候cur=cur.next继续遍历!