Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function,nums
should be[1, 3, 12, 0, 0]
.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
void moveZeroes(int* nums, int numsSize) {
int *p, *q;
int i = 0;
if (nums == NULL || numsSize <= 0){
return ;
}
p = nums;
q = p + 1;
for(i = 0; i < numsSize - 1; i ++){
if (*p == 0 && *q == 0)
{
q ++;/* 前后均不为零时,q往后继续遍历 */
continue;
}
if (*p == 0 && *q != 0){
*p = *q;
*q = 0;/* 后者为零,直接互换值 */
}
p ++;/* 指针后移 */
q ++;
}
}