编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
自己解
/**
* 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) {
if(head == NULL)
return NULL;
map<int,int> m;
ListNode* p = head;
ListNode* pre = head;
while(head)
{
if(m[head->val] == 0)
{
m[head->val]++;
pre = head;
}
else
{
pre->next = head->next;
}
head = head->next;
}
return p;
}
};
/**
* 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) {
if(head == NULL)
return NULL;
ListNode* p = head;
while(p)
{
ListNode* fast = p;
while(fast->next)
{
if(fast->next->val == p->val)
fast->next = fast->next->next;
else
fast = fast->next;
}
p = p->next;
}
return head;
}
};