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

# 83. Remove Duplicates from Sorted List

## LeetCode [**83. Remove Duplicates from Sorted List**](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/)\*\*\*\*

### Description

Given the `head` of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list **sorted** as well.

**Example 1:**

![](https://3979976701-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MWCWmbVhbhatBCAMIGH%2Fuploads%2Fgit-blob-a3db432f816d0a10d05a058e82730ac4c6a8b9be%2Fimage%20\(1\).png?alt=media)

```
Input: head = [1,1,2]
Output: [1,2]
```

**Example 2:**

![](https://3979976701-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MWCWmbVhbhatBCAMIGH%2Fuploads%2Fgit-blob-8b560257542b701af32cbfef35175e048e042e38%2Fimage%20\(2\).png?alt=media)

```
Input: head = [1,1,2,3,3]
Output: [1,2,3]
```

**Constraints:**

* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order.

### Tags

Linked List

### Solution

Traverse the linked list with two pointers `pre` and `cur` who start from `head`. We move `cur` forwardly until `pre.Val != cur.Val`, or `cur` reaches the end. Then connect `pre.Next` to `cur.` Repeat this until `pre` is null. Return the `head` at last.

### Complexity

* Time complexity: $$O(n)$$
* Space complexity: $$O(1)$$

### Code

```go
// code here.
type ListNode struct {
	Val  int
	Next *ListNode
}

func deleteDuplicates(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}

	for p := head; p != nil; p = p.Next {
		q := p.Next
		for q != nil && p.Val == q.Val {
			q = q.Next
		}
		p.Next = q
	}
	return head
}
```
