给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例1:
输入: 1->1->2
输出: 1->2
示例2:
输入:[]
输出:[]
题解一:借助vector的erase方法,配合unique()删除排序重复元素
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) // 借助vector的erase方法,配合unique()删除排序重复元素
{
if (NULL == head)
return head;
vector<int> v;
struct ListNode* p = head;
for (; NULL != p; p = p->next)
{
v.push_back(p->val);
}
v.erase(unique(v.begin(), v.end()), v.end());
struct ListNode* L = new struct ListNode(v.front());
v.erase(v.begin());
p = L;
struct ListNode* q;
while (!v.empty())
{
q = new struct ListNode(v.front());
p->next = q;
p = p->next;
v.erase(v.begin());
}
return L;
}
};
题解二:(参考别人的题解)
ListNode* deleteDuplicates(ListNode* head)
{
while (nullptr == head)
return head;
struct ListNode* p = head;
struct ListNode* next;
while (nullptr != p)
{
next = p->next; // 需判断next是否为空指针
if (nullptr != next && p->val == next->val)
{
p->next = next->next;
delete next;
}
else
{
p = p->next;
}
}
return head;
}