首先定义线性表模型以及相关的操作
public class MySqList {
private static int MAX_SIZE = 100;
/** 数组 */
public static int[] data;
/** 记录线性表的长度*/
public static int size;
/**
* 初始化线性表
*/
public static int init() {
data = new int[MAX_SIZE];
size = 0;
return size;
}
/**
* 创建一个长度为n的线性表
* @param n
* @return
*/
public static int[] createSq(int n) {
init();
if (n > MAX_SIZE) {
return null;
}
for (int i = 0; i < n; i++) {
data[i] = i+1;
}
size = n;
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[i] = data[i];
}
return temp;
}
/**
* 获取线性表,第n的位置的数据
* @param n
* @param arr
* @return
*/
public static int getValue(int n, int[] arr) {
if (n > size) {
return -1;
}
return arr[n-1];
}
/**
* 查询,线性表中值为value的数据,成功返回其位置,失败返回-1;
* @param value
* @param arr
* @return
*/
public static int searchValue(int value, int[] arr) {
for (int i = 0; i < size; i++) {
if (data[i] == value) {
return i+1;
}
}
return -1;
}
/**
* 向线性表插入一个数据,成功返回线性表长度,失败返回-1;
* @param i
* @param value
* @param arr
* @return
*/
public static int insertSq(int i, int value, int[] arr) {
if (i < i || i > size+1) {
return -1;
}
if (arr.length == MAX_SIZE) {
return -1;
}
int j = -1;
for (j = size -1; j >= i-1 ; j--) {
data [j+1] = data[j];
}
data[j+1] = value;
size++;
return size;
}
/**
* 删除第n的位置的值
* @param n
* @param arr
* @return
*/
public static int deleteSq(int n, int[] arr) {
if (n < 1 || n > size) {
return -1;
}
for (int i = n-1; i < size; i++) {
data[i] = data[i+1];
}
size--;
return size;
}
}
测试
public class SqTest {
public static void main(String[] args) {
m6();
}
private static void m6() {
int[] sq = MySqList.createSq(10);
int i = MySqList.deleteSq(11, sq);
System.out.println(i);
}
private static void m5() {
int[] sq = MySqList.createSq(10);
int i = MySqList.insertSq(5, 100, sq);
System.out.println(i);
int[] data = MySqList.data;
for (int datum : data) {
System.out.println(datum);
}
}
private static void m4() {
int[] sq = MySqList.createSq(10);
int i = MySqList.searchValue(100, sq);
System.out.println(i);
}
private static void m3() {
int[] sq = MySqList.createSq(10);
int value = MySqList.getValue(11, sq);
System.out.println(value);
}
private static void m2() {
int[] sq = MySqList.createSq(10);
for (int i : sq) {
System.out.println(i);
}
}
private static void m1() {
int init = MySqList.init();
System.out.println(init);
}
}