题目:
假定数组A[arraySize]中有多个零元素, 试写出一个函数, 将A 中所有的非零元素依次移到数组A的前端A[i]。
Array.h
#pragma once #include<iostream> using namespace std; class Array { int* data; int num; public: Array(int n) { num = n; data = new int[num]; } void creat(int* arr) { for (int i = 0; i < num; i++) { data[i] = arr[i]; } } void show() { for (int i = 0; i < num; i++) { cout << data[i] << " "; } cout << endl; } void move() { int p = 0; int temp; for (int i = 0; i < num; i++) { if (data[i] != 0) { temp = data[i]; data[i] = data[p]; data[p] = temp; p++; } } } };
main.cpp
#include"Array.h" int main() { Array L(11); int arr[] = { 0,8,3,0,4,0,5,4,0,9,0 }; L.creat(arr); L.show(); L.move(); L.show(); return 0; }
原文地址:https://www.cnblogs.com/SlowIsFast/p/12501801.html
时间: 2024-11-02 02:35:47