【题目】
编写代码,移除未排序链表中的重复节点。
来源:leetcode
链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci/
【示例】
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
【示例2】
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
【代码】
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
bool vis[20001] = {0};
public:
ListNode* removeDuplicateNodes(ListNode* head) {
if(!head||!head->next) return head;
ListNode* cur=head,*pre=head;
vis[cur->val]=true;
cur=cur->next;
while(cur){
if(vis[cur->val]){//该节点被访问过
pre->next=cur->next;
}else{//该节点没有访问过
vis[cur->val] = true;
pre=cur;
}
cur=cur->next;
}
return head;
}
};