描述
给定一个排序链表,删除所有重复的元素每个元素只留下一个。
样例
给出 1->1->2->null,返回 1->2->null
给出 1->1->2->3->3->null,返回 1->2->3->null
思考
- 需要注意的是在 while() 循环中,如果满足条件还需要继续比较,而不是跳出循环,因为 2 2 2 -> 2 2 删除重重复节点之后可能依然重复
代码
// By Lentitude
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: head node
*/
ListNode *deleteDuplicates(ListNode *head) {
// write your code here
if (head == NULL) return NULL;
ListNode *pre = head;
while (pre != NULL){
if (pre->next == NULL ) return head;
// 如果存在则循环处理,应该后续节点发生改变
while (pre->next->val == pre->val){
if (pre->next->next == NULL){
pre->next = NULL;
return head;
}else{
pre->next = pre->next->next;
}
}
pre = pre->next;
}
return head;
}
};