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.
/**
* Definition for singly-linked list.
* struct ListNode
{
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head)
{
if(NULL == head)
return NULL;
struct ListNode * p = head;
while(p->next)
{
if(p->val != p->next->val)
{
p = p->next;
}
else
{
struct ListNode * tmp = p->next;
p->next = p->next->next;
/*free tmp,if node is malloc*/
free(tmp);
}
}
return head;
}
经验教训
删除结点后,是否需要free应根据链表创建的方式来对待,比如struct ListNode a,b,c,d,e;然后各自赋值,串起来,就无需free,只有通过malloc申请的内存才需要free.
2021.05.23 C++实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* p = head;
while(p&&p->next)
{
ListNode* next = p->next;
if(p->val == next->val)
{
p->next = next->next;
}else{
p = p->next;
}
}
return head;
}
};
更简洁的实现:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* p = head;
while(p)
{
while(p->next && p->val == p->next->val)
{
p->next = p->next->next;
}
p = p->next;
}
return head;
}
};