#include <iostream>
#include <queue>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
queue<ListNode*> Q;
ListNode *p = pHead;
int count;
if (p == NULL)return NULL;
while (p != NULL)
{
count = 1;
//1 1 2 3 3 4 5 5
int temp = p->val;
while (p->next != NULL && p->next->val == temp)
{
count++;
p = p->next;
}
if (count == 1)
{
Q.push(p);
}
p = p->next;
}
if (Q.empty() == true)return NULL;
p = NULL;
while (Q.empty() == false)
{
if (p == NULL)
{
p = Q.front();
Q.pop();
pHead = p;
}
else
{
p->next = Q.front();
Q.pop();
p = p->next;
p->next = NULL;
}
}
return pHead;
}
};
void Insert(ListNode ** t,int a[],int n)
{
ListNode *p = NULL;
for (int i = 0; i < n; i++)
{
if (p == NULL)
{
p = new ListNode(a[i]);
*t=p;
}
else
{
ListNode *s = new ListNode(a[i]);
p->next = s;
p = s;
}
}
}
void Printf(ListNode *t)
{
while(t != NULL)
{
cout << t->val << " ";
t = t->next;
}
}
int main()
{
ListNode *f=NULL;
int a[] = {1,1,2,3,3,4,5,5};
Insert(&f,a,sizeof(a)/sizeof(int));
Printf(f);
cout << endl;
Solution sl;
ListNode* p = sl.deleteDuplication(f);
Printf(p);
return 0;
}
笔试题:删除链表中重复的节点
最新推荐文章于 2020-06-10 16:23:58 发布