永发信息网

java语言,设计按升序排序顺序表类,实现插入、删除操作,元素插入位置由其值决定。(数据结构)

答案:1  悬赏:10  手机版
解决时间 2021-04-03 04:23
  • 提问者网友:练爱
  • 2021-04-02 14:08
java语言,设计按升序排序顺序表类,实现插入、删除操作,元素插入位置由其值决定。(数据结构)
最佳答案
  • 五星知识达人网友:三千妖杀
  • 2021-04-02 14:44
SortedSeqList.java
public class SortedSeqList {

private int MAX_SIZE = 10;

private int[] ary = new int[MAX_SIZE];

private int length = 0;

public SortedSeqList(int[] array) {
if (array == null || array.length == 0) {
this.length = 0;
} else {
ary = array;
length = array.length;
}
}

public void clear() {
length = 0;
}

public boolean isEmpty() {
return length == 0;
}

public void delete(int index) throws Exception {
if (length == 0) {
throw new Exception("No elment to delete");
}

int newAry[] = new int[ary.length - 1];

for (int i = 0, j = 0; i < ary.length; i++) {
if (i == index) {
continue;
} else {
newAry[j++] = ary[i];
}
}

ary = newAry;
length--;
}

public int insert(int value) throws Exception {
if (length == MAX_SIZE) {
throw new Exception("List is full, can't insert more");
}

int[] newAry = new int[length + 1];

int i = 0, j = 0;
for (; i < ary.length; i++, j++) {
if (ary[i] >= value) {
newAry[j] = value;
break;
} else {
newAry[j] = ary[i];
}
}

while (i < ary.length) {
newAry[++j] = ary[i];
i++;
}

ary = newAry;
length++;

return value;

}

public void display() {
System.out.println("\nList now is: ");
for (int i = 0; i < ary.length; i++) {
System.out.print(ary[i] + "\t");
}
}

}

--------------------------SortedSeqList_ex.java
public class SortedSeqList_ex {

public static void main(String[] args) throws Exception {

int[] ary = {1, 2, 3, 5, 7};

SortedSeqList list = new SortedSeqList(ary);
list.display();
list.insert(4);
list.display();
list.delete(2);
list.display();
}

}
---------------testing result

List now is:
1 2 3 5 7
List now is:
1 2 3 4 5 7
List now is:
1 2 4 5 7
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯