数据结构例1.已知顺序表L的长度为n,试编写算法实现在顺序表中删除值为elem的数据元素

//已知顺序表L的长度为n,试编写算法实现在顺序表中删除值为elem的数据元素
//(其中n与elem从键盘输入)

# include 
# include 
# include 
using namespace std;
const maxn = 1000 + 10;

typedef struct node
{
     
	int *arr;
	int length;
	int maxsize;
}sqlist;

void createsqlist(sqlist &L)
{
     
	L.arr = (int*)malloc(maxn * sizeof(int));
	L.length = 0;
	L.maxsize = maxn;
}

void insqlist(sqlist& L, int n)
{
     
	int *p;
	printf("请依次输入数字创建一个顺序表:\n");

	for(p = L.arr; p<L.arr + n; p++)
	{
     
		scanf("%d", p);
	}

	L.length = n;
}

void outsqlist(sqlist L)
{
     
	int *p;
	printf("顺序表的元素为:\n");

	for(p = L.arr; p<L.arr+L.length; p++)
	{
     
		printf("%d ", *p);
	}

	printf("\n");
}

void deletesqlist(sqlist& L, int elem)
{
     
	int i = 0; 
	
	while(i<L.length && L.arr[i] != elem)
	{
     
		i++;
	}

	for(int j = i+1; j<L.length; j++)
	{
     
		if(L.arr[j] != elem)
		{
     
			L.arr[i++] = L.arr[j];
		}
	}

	L.length = i;
}

int main()
{
     
	//加速c++输入输出流
	ios::sync_with_stdio(false);
	cin.tie(0);


	sqlist L;
	createsqlist(L);
	int n, elem;
	
	printf("请输入n个元素: \n");
	scanf("%d", &n);
	insqlist(L, n);

	printf("请输入删除的元素值:\n");
	scanf("%d", &elem);
	deletesqlist(L, elem);
	outsqlist(L);

	return 0;
}

你可能感兴趣的:(#,数据结构,c++,算法,数据结构)