方法一:宏实现
#define SWAP(x,y) \
{ \
x = x + y; \
y = x - y; \
x = x - y; \
}
方法二:指针实现
void swap(int* px, int *py)
{
*px = *px + *py;
*py = *px - *py;
*px = *px - *py;
}
方法三:引用实现
void swap(int& rx, int& ry)
{
rx = rx + ry;
ry = rx - ry;
rx = rx - ry;
}
方法四:
void swap(int *x, int *y)
{
*x = *x ^ *y;
*y = *x ^ *y;
*x = *x ^ *y;
}
注:以上四种方法都没有用到中间变量(临时变量)
阅读(823) | 评论(0) | 转发(0) |