---
# System prepended metadata

title: 83. Remove Duplicates from Sorted List
tags: [Leetcode, list, python, c++, easy]

---

###### tags: `Leetcode` `easy` `list` `python` `c++`

# 83. Remove Duplicates from Sorted List

## [題目出處:] https://leetcode.com/problems/remove-duplicates-from-sorted-list/

## 題目:
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.

## 解題想法:
較為直觀~可以直接參考我的代碼!

## Python:
``` python=
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
    def insert(self,node):
        if self.next==None:
            self.next=ListNode(node)
        else:
            self.next.insert(node)
    def printList(self):
        head=self
        stack=[]
        while head:
            stack.append(head.val)
            head=head.next
        print(stack)

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur=head
        while cur and cur.next:
            if cur.val==cur.next.val:
                cur.next=cur.next.next
            else:
                cur=cur.next
        return head

head=ListNode(1)
head.insert(1)
head.insert(2)
head.insert(3)
head.insert(3)
head.printList()

result=Solution()
ans=result.deleteDuplicates(head)
ans.printList()
```

## C++:
``` cpp=
#include<iostream>
using namespace std;

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) {}
};

void insertNode(ListNode *head,int data){
    ListNode *tail=head;
    while (tail->next!=nullptr){
        tail=tail->next;
    }
    ListNode *new_node=new ListNode(data);
    tail->next=new_node;
}

void printList(ListNode *head){
    ListNode *tmp=head;
    while (tmp!=nullptr){
            cout<<" "<<tmp->val;
            tmp=tmp->next;
    }
    cout<<endl;
}

class Solution{
public:
    ListNode* deleteDuplicates(ListNode* head){
            ListNode *cur = head;
            while (cur && cur->next){
                if (cur->val == cur->next->val)
                    cur->next=cur->next->next;
                else
                    cur=cur->next;
            }
            return head;
    }
};

int main(){
    ListNode *head;
    head=new ListNode(1);
    insertNode(head,1);
    insertNode(head,2);
    insertNode(head,3);
    insertNode(head,3);
    cout<<"Original List: ";
    printList(head);
    Solution res;
    ListNode *ans =res.deleteDuplicates(head);
    cout<<"After delete : ";
    printList(ans);
}

```