-
题目描述
-
解题思路心得
是某年408真题,思路就是空间换时间,辅助数组记录绝对值出现与否,若该绝对值出现过就删掉。
实现的时候输入时偷偷记录了链表绝对值最大值,然后创建长度为最大值的辅助数组。
-
代码
#include <iostream>
#include <stdlib.h>
using namespace std;
struct LNode
{
int data;
LNode *next;
};
int creatlist(LNode *&L, int length)
{
LNode *p = L;
int max = 0;
for (int i = 0; i < length; i++)
{
LNode *tmp = new LNode;
cin >> tmp->data;
tmp->next = NULL;
if (abs(tmp->data) > max)
max = tmp->data;
p->next = tmp;
p = p->next;
}
return max;
}
int printlist(LNode *L)
{
LNode *p = L->next;
int count = 0;
if (p == NULL)
{
return 0;
}
while (p)
{
cout << p->data;
if (p->next != NULL)
{
cout << " ";
}
p = p->next;
count++;
}
cout << endl;
return count;
}
void funlist(LNode *&L, int max)
{
int *array = new int[max];
LNode *p=L->next;
LNode *r=L;
for (int i = 0; i < max; i++)
{
array[i]=0;
}
while (p)
{
if (array[abs(p->data)]==0)
{
array[abs(p->data)]=1;
p=p->next;
r=r->next;
}else{
r->next=p->next;
free(p);
p=r->next;
}
}
delete[]array;
}
int main()
{
int n = 0;
int max = 0;
while (1)
{
LNode *L = new LNode;
L->next = NULL;
cin >> n;
if (!n)
{
break;
}
max=creatlist(L, n);
funlist(L,max+1);
printlist(L);
}
return 0;
}