自己的解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *pre = dummy, *curr = head;
while (pre != nullptr && curr != nullptr) {
while (curr != nullptr && pre->val == curr->val) {
curr = curr->next;
}
pre->next = curr;
pre = curr;
if (curr != nullptr) {
curr = curr->next;
}
}
return head;
}
};
题解(Java版本)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur = head;
while(cur != null && cur.next != null) {
if(cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode*p=head;
while(p){
while(p->next&&p->next->val==p->val){
p->next=p->next->next;
}
p=p->next;
}
return head;
}
};