# 83. Remove Duplicates from Sorted List 删除排序链表中的重复元素

@TOC

[LeetCode]

Total Accepted: 114584 Total Submissions: 311665 Difficulty: Easy

## # 题目描述

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
``````

## # 解题方法

### # 判断相邻节点是否相等

Java代码如下：

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
while(move!=null && move.next!=null){
if(move.next.val == move.val){
move.next=move.next.next;
}else{
move=move.next;
}
}

}
}
``````

``````# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""
while cur:
if cur.val == prev.val:
prev.next = cur.next
else:
prev = cur
cur = cur.next
``````

C++版本如下：

``````/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
while (cur) {
if (prev->val == cur->val) {
prev->next = cur->next;
} else {
prev = cur;
}
cur = cur->next;
}
}
};
``````

### # 使用set

``````# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
"""
:rtype: ListNode
"""
val_set = set()
root = ListNode(0)
else:
return root.next
``````

### # 使用列表

python代码如下：

``````# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""
deque = []
while move:
while deque and deque[-1].val == move.val:
deque.pop()
deque.append(move)
move = move.next
for i in range(len(deque) - 1):
deque[i].next = deque[i + 1]
return deque[0]
``````

### # 递归

``````# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):