您的位置:首页 > 其它

Leetcode Remove Duplicates from Sorted List II

2016-12-24 12:03 260 查看
题意:删除列表中重复的所有元素。

思路:用hash表记录重复的元素,在链表中删除。

/**
* 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 || head->next == NULL) return head;

ListNode *myhead = new ListNode(0);
myhead->next = head;
auto next = myhead->next;
map<int, int> m;
while(next) {
m[next->val] ++;
next = next->next;
}

next = myhead;
while(next) {
auto tempnext = next->next;
while(tempnext && m[tempnext->val] > 1) {
tempnext = tempnext->next;
}
next->next = tempnext;
next = next->next;
}

return myhead->next;
}
};

递归写法值的思考。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode