2.1.11 —线性表—Remove Element

来源:互联网 发布:查询进口商品数据 编辑:程序博客网 时间:2024/06/03 16:33
描述
Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

#include<iostream>using namespace std;int RemoveElement(int a[], int n,int value){if (a == NULL || n <= 0)return 0;int i = 0;int k = 0;for (; i < n; ){if (a[i] == value){i++;}else{a[k] = a[i];k++;i++;}}return k;}int main(){const int n = 10;int a[n] = { 1, 2, 4, 4, 4, 4, 5, 6, 6, 6 };int value = 6;int k = RemoveElement(a, n, value);for (int i = 0; i < k; i++)cout << a[i] << " ";cout << endl;}


原创粉丝点击