delete the element of array

本文介绍了一种在C语言中从数组中删除特定元素的方法。该方法通过移动被删除元素之后的所有元素来填补空缺,并考虑了数组中元素数量的变化。通过对数组进行遍历和条件判断,实现了对指定元素的有效移除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The first method use less space but wate time!

#include <stdio.h>

#define MAXSIZE 100

void delete_element(int arr[], int length);

int main(void)
{
	int a[MAXSIZE] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
	printf("Before delete array is:\n");
	int i = 0;
	while(a[i]){
		printf("%d, ",a[i]);
		++i;
	}
	printf("\n");

	delete_element(a, MAXSIZE);
	
	i = 0;
	while(a[i]){
		printf("%d, ",a[i]);
		++i;
	}
	printf("\n");
	return 0;
}

void delete_element(int arr[], int length)
{
	if(NULL == arr || length <= 0)
		return ;

	int i = 0;
	int num_deleted = 0;
	int original_length = 0;
	
	// Find the number of element that will be deleted
	while(arr[i] != '\0' && i < length){
		++ original_length;
		if(0 == (arr[i] % 3))
			++ num_deleted;
		++i;
	}

	--i;
	int new_length = original_length;
	int walk_len = 0;
	int temp_len = 0;
	while(i >= 0){
		++walk_len;
		if(0 == (arr[i] % 3)){
			if(1 == walk_len) // replace the deleted element with '\0'
				arr[i] = '\0';
			else{
				temp_len = walk_len;
				// move the elements behind the deleted element
				while(temp_len >=0){
					arr[new_length-temp_len] = arr[new_length - (temp_len - 1)];
					--temp_len;

				}
				--new_length;
				--walk_len;
			}
		}
		--i;
	}// while
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值