编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeDuplicateNodes(ListNode* head) {
unordered_map<int, int> m;
ListNode *res = new ListNode(0);
ListNode *now = res;
while(head){
m[head->val]++;
if(m[head->val]==1){
now->next = head;
now = now->next;
head = head->next;
}
else{
now->next=NULL;
head = head->next;
}
}
return res->next;
}
};