删除链表中重复的结点
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表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)
{
if(pHead == NULL)
return NULL;
ListNode* p = pHead;
vector<int> v;
while(p)
{
v.push_back(p->val);
p = p->next;
}
ListNode* k = new ListNode(0);
ListNode* pc= k;
for(int i = 0;i < v.size();i++)
{
if(count(v.begin(),v.end(),v[i]) == 1)
{
ListNode* pm = new ListNode(0);
pm->val = v[i];
pm->next = NULL;
pc->next = pm;
pc = pm;
}
/*
if(count(v.begin(),v.end(),v[i]) == 1)
{
ListNode* pm = new ListNode(V[i]);
pc->next = pm;
pc = pm;
}
*/
}
return k->next;
}
};
如果题目是,重复节点仅保留一个
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(pHead == NULL)
return NULL;
ListNode* p = pHead;
vector<int> v;
while(p)
{
if(count(v.begin(),v.end(),p->val) == 0)
v.push_back(p->val);
p = p->next;
}
ListNode* k = new ListNode(0);
ListNode* pc= k;
for(int i = 0;i < v.size();i++)
{
ListNode* pm = new ListNode(0);
pm->val = v[i];
pm->next = NULL;
pc->next = pm;
pc = pm;
}
/*
for(int i = 0;i < v.size();i++)
{
ListNode* pm = new ListNode(V[i]);
pc->next = pm;
pc = pm;
}
*/
return k->next;
}
};
递归实现删除重复节点
class Solution {
public:
ListNode* deleteDuplication(ListNode* head)
{
if (head == NULL)
return NULL;
if (head != NULL&&head->next == NULL)
return head;
ListNode* cur;
if (head->val == head->next->val)
{
cur = head->next->next;
while (cur != NULL&&cur->val == head->val)
cur = cur->next;
return deleteDuplication(cur);
}
else {
cur = head->next;
head->next = deleteDuplication(cur);
return head;
}
}
};