一、无序表
int DelX2Y(Sqlist& s, int x, int y) {
if (s.length == 0) {
cout << "数组为空无法删除" << endl;
return 0;
}
if (x > y) {
cout << "参数无效" << endl;
return 0;
}
int count = 0;
for (int i = 0; i < s.length; i++) {
if (s.a[i]<=y && s.a[i]>=x) count++;
if (s.a[i] > y) {
s.a[i - count] = s.a[i];
}
}
if (count ==0) {
cout << "没有满足条件的元素" << endl;
return 0;
}
s.length = s.length - count;
}
结果:
二、有序表
有序的情况不需要这么复杂,直接前面遍历找到第一个满足的元素,从后往前遍历找到最后一个满足的元素,删除之间的元素就可以
int DelX2Y_ordered(Sqlist& s, int x, int y) {
if (s.length == 0) {
cout << "数组为空无法删除" << endl;
return 0;
}
if (x > y) {
cout << "参数无效" << endl;
return 0;
}
if (y<s.a[0] || x>s.a[s.length - 1]) {
cout << "没有满足条件的元素" << endl;
return 0;
}
int count = 0;
int i, j;
for (i=0; i < s.length; i++) {
if (s.a[i] >= x) break;
}
for (j = s.length - 1; j > 0; j--) {
if (s.a[j] <= y)break;
}
for (int k = i; k <= j; k++)
s.a[k] = s.a[k + j - i + 1];
s.length = s.length - (j-i+1);
}
三、删除有序表中的重复元素
思想:设置两个指针: i 和 j,i,j初始都为0,用 j 循环遍历数组,当 i 和 j 所指的元素不相等时令a[i+1]=a[j],i++,遍历完成后数组长度改为i。
int DelRepeat(Sqlist& s) {
int i = 0, j = 0;
if (s.length == 0)return 0;
for (j = 0; j < s.length; j++) {
if (s.a[i] != s.a[j]) {
s.a[i + 1] = s.a[j];
i++;
}
}
s.length = i;
cout << "数组长度为" << i << endl;
}
四、合并两个有序表并返回一个新的有序表
互相比较依次添加就可以
void AB2C(Sqlist A,Sqlist B,Sqlist &C) {
if (A.length == 0 && B.length != 0) {
for (int i = 0; i < B.length; i++) {
C.a[i] = B.a[i];
}
}
if (B.length == 0 && A.length != 0) {
for (int i = 0; i < A.length; i++) {
C.a[i] = A.a[i];
}
}
if (B.length != 0 && A.length != 0) {
int i = 0, j = 0, k = 0;
while (i<A.length&&j<B.length) {
if (A.a[i] <= B.a[j]) {
C.a[k++] = A.a[i++];
}
else
C.a[k++] = B.a[j++];
}
while (i < A.length)
C.a[k++] = A.a[i++];
while (j < B.length)
C.a[k++] = B.a[j++];
}
}