# Remove Duplicates from Sorted List

## Question

### Problem Statement

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

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

## 题解

### Python

"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@return: A ListNode
"""
while curt:
while curt.next and curt.next.val == curt.val:
curt.next = curt.next.next
curt = curt.next


### C++

/**
* Definition of ListNode
* class ListNode {
* public:
*     int val;
*     ListNode *next;
*     ListNode(int val) {
*         this->val = val;
*         this->next = NULL;
*     }
* }
*/
class Solution {
public:
/**
*/
while (curr != NULL) {
while (curr->next != NULL && curr->val == curr->next->val) {
ListNode *temp = curr->next;
curr->next = curr->next->next;
delete(temp);
temp = NULL;
}
curr = curr->next;
}

}
};


### Java

/**
* Definition for ListNode
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
/**
*/
public static ListNode deleteDuplicates(ListNode head) {
while (curr != null) {
while (curr.next != null && curr.val == curr.next.val) {
curr.next = curr.next.next;
}
curr = curr.next;
}

}
}


### 源码分析

2. 遍历链表，curr->val == curr->next->val时，保存curr->next，便于后面释放内存(非C/C++无需手动管理内存)
3. 不相等时移动当前节点至下一节点，注意这个步骤必须包含在else中，否则逻辑较为复杂

while 循环处也可使用curr != null && curr.next != null, 这样就不用单独判断head 是否为空了，但是这样会降低遍历的效率，因为需要判断两处。使用双重while循环可只在内循环处判断，避免了冗余的判断，谢谢 @xuewei4d 提供的思路。