# include <bits/stdc++.h>
using namespace std;
struct list_node{
int val;
struct list_node * next;
};
list_node * input_list()
{
int val, n;
scanf("%d", &n);
list_node * phead = new list_node();
list_node * cur_pnode = phead;
for (int i = 1; i <= n; ++i) {
scanf("%d", &val);
if (i == 1) {
cur_pnode->val = val;
cur_pnode->next = NULL;
}
else {
list_node * new_pnode = new list_node();
new_pnode->val = val;
new_pnode->next = NULL;
cur_pnode->next = new_pnode;
cur_pnode = new_pnode;
}
}
return phead;
}
list_node * remove_rep(list_node * head)
{
//////在下面完成代码
//本题应该没有时间复杂度为O(N)空间复杂度为O(1)的做法,如果有请务必让我学习一下
//O(N),O(N)的解法就太多了,这里采用哈希表
if(head==NULL||head->next==NULL)
return head;
//头结点肯定会保留
map<int, int> hashMap;//key的含义为节点值,value的含义为这个值出现的次数
hashMap[head->val]++;//先把头结点的记录放进去
list_node*pre=head,*cur=head->next;
while(cur){
if(hashMap.find(cur->val)==hashMap.end()){//说明这是第一次遇到这个节点
hashMap[cur->val]++;
pre=cur;
cur=cur->next;
}
else{//说明之前已经遇到过该节点了,当前节点要删除
pre->next=cur->next;
delete cur;
cur=pre->next;
}
}
return head;
}
void print_list(list_node * head)
{
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
puts("");
}
int main ()
{
list_node * head = input_list();
list_node * new_head = remove_rep(head);
print_list(new_head);
return 0;
}
using namespace std;
struct list_node{
int val;
struct list_node * next;
};
list_node * input_list()
{
int val, n;
scanf("%d", &n);
list_node * phead = new list_node();
list_node * cur_pnode = phead;
for (int i = 1; i <= n; ++i) {
scanf("%d", &val);
if (i == 1) {
cur_pnode->val = val;
cur_pnode->next = NULL;
}
else {
list_node * new_pnode = new list_node();
new_pnode->val = val;
new_pnode->next = NULL;
cur_pnode->next = new_pnode;
cur_pnode = new_pnode;
}
}
return phead;
}
list_node * remove_rep(list_node * head)
{
//////在下面完成代码
//本题应该没有时间复杂度为O(N)空间复杂度为O(1)的做法,如果有请务必让我学习一下
//O(N),O(N)的解法就太多了,这里采用哈希表
if(head==NULL||head->next==NULL)
return head;
//头结点肯定会保留
map<int, int> hashMap;//key的含义为节点值,value的含义为这个值出现的次数
hashMap[head->val]++;//先把头结点的记录放进去
list_node*pre=head,*cur=head->next;
while(cur){
if(hashMap.find(cur->val)==hashMap.end()){//说明这是第一次遇到这个节点
hashMap[cur->val]++;
pre=cur;
cur=cur->next;
}
else{//说明之前已经遇到过该节点了,当前节点要删除
pre->next=cur->next;
delete cur;
cur=pre->next;
}
}
return head;
}
void print_list(list_node * head)
{
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
puts("");
}
int main ()
{
list_node * head = input_list();
list_node * new_head = remove_rep(head);
print_list(new_head);
return 0;
}