# Remove Duplicates from Sorted List

> Given a sorted linked list, delete all duplicates such that each element appear only once.

> For example,

> Given 1->1->2, return 1->2.

> Given 1->1->2->3->3, return 1->2->3.

```c++
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
}

int val = head->val;
ListNode* p = head;
while(p && p->next) {
if(p->next->val != val) {
val = p->next->val;
p = p->next;
} else {
//删除next
ListNode* n = p->next->next;
p->next = n;
}
}

}
};
```

# Remove Duplicates from Sorted List II

> Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

> For example,

> Given 1->2->3->3->4->4->5, return 1->2->5.

> Given 1->1->1->2->3, return 2->3.

```c++
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
}

ListNode dummy(0);
ListNode* prev = &dummy;
ListNode* p = head;
while(p && p->next) {
//如果没有重复，则prev为p，next为p->next
if(p->val != p->next->val) {
prev = p;
p = p->next;
} else {
//如果有重复，则继续遍历，直到不重复的节点
int val = p->val;
ListNode* n = p->next->next;
while(n) {
if(n->val != val) {
break;
}
n = n->next;
}

//删除重复节点
prev->next = n;
p = n;
}
}
return dummy.next;
}
};
```