LeetCode---Remove Duplicates from Sorted List II

来源:互联网 发布:java判断数字奇偶 编辑:程序博客网 时间:2024/05/22 14:13

题目大意:给出一个已排序的链表,删除链表中元素个数不为1的链表节点。

算法思想:

1.遍历链表,采用容器记录链表节点,同时为每个节点元素计数。

2.遍历容器,将节点元素个数为1的节点连接起来,释放元素个数大于1的节点。

3.返回修改后的链表。

注意为了方便链表的操作,设置了一个头结点。

代码如下:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* deleteDuplicates(ListNode* head) {        if(head==NULL) return head;        map<int,ListNode*> Node;        map<int,int> Num;        ListNode* p=head;        while(p!=NULL){                        Node.insert(make_pair(p->val,p));            Num[p->val]++;            p=p->next;                }        map<int,ListNode*>::iterator pos;        map<int,int>::iterator pos1;        ListNode* wzg=new ListNode(0);        p=wzg;        for(pos=Node.begin(),pos1=Num.begin();pos!=Node.end()&&pos1!=Num.end();++pos1,++pos){            if(Num[pos1->first]==1){              p->next=pos->second;              p=p->next;            }            else delete pos->second;        }        if(p!=NULL)           p->next=NULL;         head=wzg->next;         delete wzg;         return head;            }};


0 0
原创粉丝点击