c++去除有序顺序表一定范围中的数

#include<iostream>

#define MaxSize 50
#define ElemType int
using namespace std;

typedef struct {
	ElemType data[MaxSize];
	int length;
}SqList;

void Init(SqList &L) {
	ElemType a;
	int n;  //初始的个数
	cout << "Please enter the number of elements : ";
	cin >> n;
	cout << "Please enter elements:";
	for (int i = 0; i < n; i++) {
		cin >> a;
		L.data[i] = a;
	}
	L.length = n;
}

bool delimit(SqList &L, ElemType s, ElemType t) { //去除有序表一定范围中的数
	int i = 0;
	int tag = -1;
	int count = 0;  //统计在范围内的个数
	if (L.length == 0 || s>t) {  //如果不符合范围
		return false;
	}
	else {
		while (i < L.length) {
			if (L.data[i] >= s && tag==-1) {
				tag = i;   //标记在范围内的第一个数的下标
				if (L.data[i] <= t) {
					count++;
					i++;
				}
				else {
					break;
				}
			}
			else {
				if (L.data[i] >= s) {
					if (L.data[i] <= t) {
						count++;
						i++;
					}
					else {
						break;
					}
				}
				else {
					i++;
				}
			}
		}
		//接下来开始移位
		int j = tag;
		while (j < L.length - count) {  //防止下标越界
			if (j + count < L.length) {
				L.data[j] = L.data[j + count]; //赋值
				j++;
			}
		}
		L.length = L.length - count;
		return true;
	}
}

void Print(SqList &L) {   //输出顺序表中的元素
	int i;
	for (i = 0; i < L.length; i++) {
		cout << L.data[i] << " ";
	}
	cout << endl;
}

int main() {

	SqList L;
	Init(L);  //初始化
	delimit(L,4,8);
	Print(L);
	system("pause");
	return 0;
}

/*
12
1 2 3 4 5 6 7 8 9 10 11 12
*/


猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/80113956