83. 删除排序链表中的重复元素
思路:双指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* left = head;
ListNode* right = NULL;
while (left != NULL && left->next != NULL) {
right = left->next;
if (left->val == right->val) {
while (right != NULL && left->val == right->val) {
right = right->next;
}
left->next = right;
}
left = left->next;
}
return head;
}
};
改进一下?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* left = head;
ListNode* right;
while (left != NULL)
{
right = left->next;
if (right != NULL)
{
while (right != NULL && right->val == left->val)
{
right = right->next;
}
left->next = right;
}
left = left->next;
}
return head;
}
};