# Remove Duplicates from Sorted List

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

**Example 1:**

```
Input: 1->1->2
Output: 1->2
```

**Example 2:**

```
Input: 1->1->2->3->3
Output: 1->2->3
```

## Solution

Typical Two Pointers Approach ()

```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 p, q;
        p = head;
        q = head;
        while (q != null) {
            if (q.val != p.val) {
                p.next = q;
                p = p.next;
            }
            q = q.next;
        }

        if (p != null) {
            p.next = null;
        }
        return head;
    }
}
```

Even Simpler Approach - Time O(n), Space O(1) - [LeetCode official](https://leetcode.com/problems/remove-duplicates-from-sorted-list/solution/) (0ms, 100%)

> All nodes in the list up to the pointer `current` do not contain duplicate elements.

```java
public ListNode deleteDuplicates(ListNode head) {
    ListNode current = head;
    while (current != null && current.next != null) {
        if (current.next.val == current.val) {
            current.next = current.next.next;
        } else {
            current = current.next;
        }
    }
    return head;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://aaronice.gitbook.io/lintcode/linked_list/remove-duplicates-from-sorted-list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
