1)题目:
从有序顺序表中删除其值在给定s与t之间(要求s<t)的所有元素,如果s或t不合理或顺序表为空,则显示出错误信息并退出运行。
2)思路:
从头往后遍历数组,先找到s所在的位置,再从s开始往后找到t,统计s到t之间一共d个元素;t之后的元素依次往前移动d位,最后从后往前删除移动后空出来的d个空位。
3)代码:
源码中使用到的ArrrayList,是调用的是自己实现的ArrayList,自己实现的ArrayList源码地址:https://blog.youkuaiyun.com/u012441545/article/details/89667486
package com.sam.datastruct.arrayList;
import java.util.Random;
public class P2_04 {
public void function(ArrayList<Integer> list, Integer s, Integer t){
if (list == null || list.isEmpty() || s >= t) {
System.err.println("then input is error!");
return;
}
int d = 0;
int index = 0;
while (list.get(index) <= s){
++ index;
}
while (list.get(index + (d)) < t){
++ d;
}
for(int i = index + d; i < list.size(); ++i){
list.update(list.get(i), index++);
}
for(int i = 1; i <= d; ++i){
list.remove();
}
}
public static void main(String[] args) {
P2_04 p = new P2_04();
ArrayList<Integer> list = new ArrayList<>();
list.initacs(20);
Random random = new Random();
Integer s = random.nextInt(10) + 1;
Integer t = 10 + random.nextInt(10);
System.out.println("s: " + s + ", t:" + t);
p.function(list, s, t);
System.out.println(list.toString());
}
}