package List;
import javax.naming.PartialResultException;
import java.awt.image.BandedSampleModel;
public class List {
private int[] arr;
private static int length;
public List(int length){
if(length >= 0){
this.arr = new int[length]; //顺序表最大长度
this.length = 0; //实际大小
}else {
System.out.println("你给的初始值: " + length + "不能小于0");
}
}
public static int size(){
return length;
}
public void Insert(int value , int index){
for(int i = this.length - 1 ; i >= index ; i--){
arr[i+1] = arr[i];
}
arr[index] = value;
this.length++;
}
public void print() {
for (int i = 0; i <= this.length - 1; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public void clear(){
this.length = 0;
}
public boolean isEmpty(){
return length==0;
}
public int get(int i){
return arr[i];
}
public int indexOf(int e){
int count = 0;
for(int k = 0 ; k <=length ; k++){
count++;
if(arr[k]==e)
return count;
}
return -1;
}
public int getPre(int e){
int count = 0 ;
for(int i = 0 ; i<=length ; i++){
count++;
if(arr[i]==e)
return arr[count-2];
}
return -1;
}
public int getNext(int e){
int count = 0 ;
for(int i = 0 ; i<=length ; i++){
count++;
if(arr[i]==e)
return arr[count];
}
return -1;
}
public int removebyindex(int i){
int ans = arr[i-1];
for(int k = i-1 ; k<length ; k++){
arr[k] = arr[k+1];
}
length--;
return ans;
}
public int removebyvalue(int e){
int count = 0;
int ans = 0 ;
for(int i = 0 ; i < length ; i ++){
count++;
if(arr[i]==e) {
ans = arr[i];
break;
}
}
for(int j = count-1 ; j<length ;j++){
arr[j]=arr[j+1];
}
length--;
return ans;
}
public static void main(String[] args) {
List list = new List(5);
// for(int i = 0 ; i < 5 ; i++){
// list.Insert(i+1,i);
// }
list.Insert(1,0);
list.Insert(2,0);
list.Insert(3,0);
list.Insert(4,0);
list.print();
System.out.println("该顺序表长度为:"+List.size());
// list.clear();
list.print();
System.out.println("该顺序表长度为:"+List.size());
System.out.println("该表为空吗:"+list.isEmpty());
System.out.println("第3个元素为:"+ list.get(2));
System.out.println("第一个等于2的元素位序为:"+list.indexOf(2));
System.out.println("元素为3的前面一个元素为:"+list.getPre(3));
System.out.println("元素为3的后面一个元素为:"+list.getNext(3));
// System.out.println("删除第2个元素:"+"'"+list.removebyindex(2)+"'"+"之后的顺序表为:");
// list.print();
// System.out.println("表长为:"+length);
System.out.println("删除的元素为:"+list.removebyvalue(3));
System.out.println("删除之后的列表为:");
list.print();
System.out.println("表长为:"+length);
// list.print();;
}
}
运行结果:
4 3 2 1
该顺序表长度为:4
4 3 2 1
该顺序表长度为:4
该表为空吗:false
第3个元素为:2
第一个等于2的元素位序为:3
元素为3的前面一个元素为:4
元素为3的后面一个元素为:2
删除的元素为:3
删除之后的列表为:
4 2 1
表长为:3