# Remove Duplicates from Sorted List

## Question

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

Example
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.


## 題解

### Python

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

class Solution:
# @return {ListNode}
return None

while node.next is not None:
if node.val == node.next.val:
node.next = node.next.next
else:
node = node.next



### C++

/**
* Definition of ListNode
* class ListNode {
* public:
*     int val;
*     ListNode *next;
*     ListNode(int val) {
*         this->val = val;
*         this->next = NULL;
*     }
* }
*/
class Solution {
public:
/**
*/
return NULL;
}

while (node->next != NULL) {
if (node->val == node->next->val) {
ListNode *temp = node->next;
node->next = node->next->next;
delete temp;
} else {
node = node->next;
}
}

}
};


### Java

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
if (head == null) return null;

while (node.next != null) {
if (node.val == node.next.val) {
node.next = node.next.next;
} else {
node = node.next;
}
}

}
}


### 源碼分析

2. 遍歷鏈表，node->val == node->next->val時，保存node->next，便於後面釋放記憶體(非C/C++無需手動管理記憶體)
3. 不相等時移動當前節點至下一節點，注意這個步驟必須包含在else中，否則邏輯較為複雜

while 循環處也可使用node != null && node->next != null, 這樣就不用單獨判斷head 是否為空了，但是這樣會降低遍歷的效率，因為需要判斷兩處。