csu1217: 奇数个的那个数

给定些数字,这些数中只有一个数出现了奇数次,找出这个数。

本来用了STL set,MLE了,改为手写式的set(链表),注意一点:插入操作与删除操作不会并存。

别人的代码真短。。

//1217
# include <stdio.h>
# include <stdlib.h>
typedef struct atom
{
int key;
struct atom *next;
} atom;

int main()
{
int n, t;
atom *set, *tmp, *x, *y;
while (scanf("%d", &n)==1)
{
if (n > 0)
{
set = (atom *)malloc(sizeof(atom));
scanf("%d", &(set->key));
set->next = NULL;
--n;
}
while(n > 0)
{
x = set;
scanf("%d", &t);
if (set == NULL)
{
set = (atom *)malloc(sizeof(atom));
set->key = t;
set->next = NULL;
} else {
while(x!=NULL && x->key!=t) {y=x;x=x->next;}
if (x == NULL)
{
tmp = (atom *)malloc(sizeof(atom));
tmp->key = t;
y->next = tmp;
tmp->next = NULL;
}
else if(x == set)
{
if (x->next == NULL) {free(set);set=NULL;}
else {set = set->next;free(x);}
} else {y->next = x->next;free(x);}
}
--n;
}
printf("%d\n", set->key);
free(set);set = NULL;
}
return 0;
}


2012-2-19 

今天看到一个类似的题,是找出两个分别只出现一次的数,大牛给的题解中使用了位运算,我就想到了这道题。。原来可以这样:

/*csu 1217(2) */
# include <stdio.h>
int main()
{
int n, x, ans;
while (scanf("%d", &n) != EOF)
{
ans = 0;
for ( ; n > 0; --n)
{
scanf("%d", &x);
ans ^= x;
}
printf("%d\n", ans);
}
return 0;
}



原文地址:https://www.cnblogs.com/JMDWQ/p/2356513.html