本题的题目要求如下:
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
.
举一个例子说明本题的基本算法:
1->1->1->1->2->3
取一个指针ptr1指向第一个1,另外一个ptr2指向这个指针的next,如果跟ptr2指向的和ptr1指针指向的元素相等,则将ptr2继续向后移动一位,直到不一样位置,比如,此时ptr2指向2,这是讲ptr1->next指向现在的ptr2,之后重复这种操作。。
详细代码如下:
<pre name="code" class="cpp">/**
* 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) {
if (head == nullptr) {
return head;
}
ListNode* virtual_head = new ListNode(-1);
virtual_head->next = head;
int tmp = head->val;
ListNode* prev = head;
head = head->next;
while (head != nullptr) {
if (tmp != head->val) {
prev->next = head;
prev = head;
tmp = prev->val;
}
head = head->next;
}
prev->next = head;
return virtual_head->next;
}
};
上一个版本应该是有内存泄漏的,现在写了一个应该避免了内存泄漏的版本。。如果大家觉得还是不对,希望不吝赐教:
/**
* 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* cur = head;
while (cur != nullptr) {
ListNode* tmp = cur->next;
while (tmp != nullptr and cur->val == tmp->val) {
ListNode* del = tmp;
tmp = tmp->next;
cur->next = tmp;
delete del;
}
cur = cur->next;
}
return head;
}
};