笔试题:删除链表中重复的节点

来源:互联网 发布:无法修改mac地址 编辑:程序博客网 时间:2024/04/29 04:35
#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;}
0 0
原创粉丝点击