描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
算法
网上很多人的算法框架如下,但是只是单纯的链接结点,没有释放原结点的内存,不够优化。下面是我改进后的版本
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
ListNode *vhead = new ListNode(-1);
vhead->next = pHead;
ListNode *pre = vhead, *cur = pHead;
ListNode *tmp = nullptr; //临时指针,用于释放内存
while (cur) {
if (cur->next && cur->val == cur->next->val) {
while (cur->next && cur->val == cur->next->val) {
tmp = cur;
cur = cur->next;
delete tmp;
}
tmp = cur;
cur = cur->next;
delete tmp;
pre->next = cur;
}
else {
pre = cur;
cur = cur->next;
}
}
return vhead->next;
}
};