public class SqList { private int[] data; private int length; public SqList() { data = new int[30]; length = 0; } public boolean empty() { return length == 0; } public int length() { return length; } public void display() { int i; for(i=0; i<length-1; i++) { System.out.print(data[i]+"->"); } System.out.println(data[i]); } public int[] get(int i) { int[] arr = new int[2]; if(i<1 || i>length) { arr[0] = 0; return arr; } arr[0] = 1; arr[1] = data[i-1]; return arr; } public int locate(int e) { int i=0; while(i<length && data[i]!=e) { i++; } if(i == length) return 0; else return i+1; } public boolean insert(int i, int e) { if(i<1 || i>length) { return false; } i--; for(int j=length; j>i; j--) { data[j] = data[j-1]; } data[i] = e; length ++; return true; } public int[] delete(int i) { int[] arr = new int[2]; if(i<1 || i>length) { arr[0] = 0; return arr; } i--; arr[0] = 1; arr[1] = data[i]; for(int j=i; j<length-1; j++) { data[j] = data[j+1]; } length--; return arr; } public void create(int[] arr, int n) { for(int i=0; i<n; i++) { data[i] = arr[i]; } length = n; } public static void main(String[] args) { int[] arr = new int[]{5,6,1,6,9,3,7,8}; SqList list = new SqList(); list.create(arr, arr.length); System.out.println(list.empty()); System.out.println(list.length()); list.display(); if(list.get(3)[0] == 0) { System.out.println("error"); } else { System.out.println(list.get(3)[1]); } if(list.get(0)[0] == 0) { System.out.println("error"); } else { System.out.println(list.get(0)[1]); } System.out.println(list.locate(6)); System.out.println(list.locate(4)); if(!list.insert(0, 4)) { System.out.println("error"); } else { list.display(); } if(!list.insert(4, 4)) { System.out.println("error"); } else { list.display(); } int[] res = list.delete(0); if(res[0] == 0) { System.out.println("error"); } else { System.out.println("delete "+res[1]); list.display(); } res = list.delete(6); if(res[0] == 0) { System.out.println("error"); } else { System.out.println("delete "+res[1]); list.display(); } } }
结果:
false 8 5->6->1->6->9->3->7->8 1 error 2 0 error 5->6->1->4->6->9->3->7->8 error delete 9 5->6->1->4->6->3->7->8
时间: 2024-10-09 19:50:50