> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/linked-list/82-remove-duplicates-from-sorted-list-ii.md).

# 82 Remove Duplicates from Sorted List II

## 82. [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/)

## 1. Question

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinctnumbers 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`.

## 2. Implementation

```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 dummy = new ListNode(0);
        dummy.next = head;

        ListNode preNode = dummy, curNode = head;

        while (curNode != null) {
            while (curNode.next != null && curNode.val == curNode.next.val) {
                curNode = curNode.next;
            } 

            if (preNode.next != curNode) {
                preNode.next = curNode.next;
            }
            else {
                preNode = preNode.next;
            }
            curNode = curNode.next;
        }
        return dummy.next;
    }
}
```

## 3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)
