#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;
}
筆試題:刪除鏈表中重複的節點
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.