6-3 xcu-sjjg-java-List-3 最大元素后插入 (12 分)
编写算法:有一个非空整数顺序表L,其中元素值可能重复出现,设计一个算法,在最后一个最大值元素之后插入一个值为x的元素。
函数接口定义:
方法接口:
public void InsAfterOfMax (int x)
参数 x 表示要插入的元素。
裁判测试程序样例:
import java.util.Scanner;
class Input {
private static Scanner sc = new Scanner(System.in);
static int inputInt(){
return sc.nextInt();
}
}
class SqList
{
int [] listElem;
int curLen;
public SqList( ) // 创建n个元素构造的顺序表
{
listElem = new int[100];
int n = Input.inputInt();
for(int i = 0 ; i<n ;i++ )
{
listElem[i] = Input.inputInt();
}
curLen = n;
}
//输出所有元素
public void display()
{
int i;
for( i = 0 ; i <curLen ; i++)
{
System.out.print( listElem[i]+" ");
}
}
/* 请在这里填写答案 */
}
public class Main{
public static void main(String args[]){
SqList L = new SqList( );
int e = Input.inputInt();
L.InsAfterOfMax(e);
L.display();
}
}
输入样例:
输入两行,第一行由n+1个整数组成,第1个数表示线性表的元素个数,紧接着n个整数 表示 线性表元素,第二行有1个整数,表示要插入的元素。例如:
5 1 3 7 5 2
4
结尾无空行
输出样例:
输出结果只有一行,是插入后的线性表的所有元素。
1 3 7 4 5 2
结尾无空行
输入样例:
5 1 3 7 7 5
4
结尾无空行
输出样例:
1 3 7 7 4 5
结尾无空行
代码:
public void InsAfterOfMax(int x) {
int max = 0;
max = listElem[0];
int k = 0;
for (int i = 0; i < curLen ; i++) {
if (max <= listElem[i]) {
max = listElem[i];
k = i;
}
}
if (curLen == listElem.length)//防止数据溢出
updatacapacity(this.curLen * 2);
for (int j = curLen ; j > k; j--) {
listElem[j] = listElem[j - 1];
}
listElem[k + 1] = x;
curLen++;
}
private void updatacapacity(int n) {//创造新的方法对满数据情况下扩容
int newdata[] = new int[n];
for (int i = 0; i < listElem.length; i++) {
newdata[i] = listElem[i];
}
listElem = newdata;
}