[数据结构] __ 两个关于顺序表的小练习

2019-05-08  本文已影响0人  葛木小舍先生丶

/**
 * 声明一个顺序表类,
 */
class SeqList{
    private int len=0;  // 声明一个变量来标注元素长度,并初始化为0.
    private int[] a = new int[10];  // 数组,
    // 构造方法
    SeqList(){
    }
    // 插入方法,使插入的数自动按递减顺序排列输出.分解思路,可以先将元素进行尾插入,然后进行一次排序.
    void insert(int ainsert) {
        // 使用尾插入插入元素
        a[len] = ainsert;
        len++;
        // 这里使用的是最简单的选择排序.
        for (int i = 0; i < a.length - 1; i++) { // 控制循环的轮次,总共需要n-1次.
            int min = i; // 声明成员变量,用来储存最小元素的下标.
            for (int j = i + 1; j < a.length; j++) { // 内层for循环,j=i+1是为了将序列分开为i表示的已排列,和i+1及之后的未排列两部分,
                if (a[j] > a[min]) {  // 判断条件,在未排列(即i+1之后的序列.)序列里找到最小元素
                    min = j; // 将最小元素的下标保存到成员变量min中.
                }
            }
            if (min != i) {  // 判断条件,判断最小元素是否和当前首位元素相同,
                // 交换位置.
                int temp = a[i];
                a[i] = a[min];
                a[min] = temp;
            }
        }
    }
    // 删除方法,删除从某点起后的n位元素.(即删除a+1到a+n位数.)我们采用移位赋值的方式进行删除操作.
    void delete(int start,int Number){
        if(start<=0 || start>len){
            System.out.println("开始位置错误");
        }else if ((start+Number)>len){
            System.out.println("没有足够可供删除的元素");
        }else
        {
            for (int j=start;j<len-Number;j++){  // 通过for循环重新给数组赋值.
                a[j+1] = a[j+Number+1];
            }
            len-=Number;
        }
    }
    // 声明输出数组方法.
    void tostring(){
        for (int i=0;i<len;i++){
            System.out.print(a[i]+",");
        }
        System.out.println("表长:"+len);
    }
}

测试类,声明主方法,new对象进行测试.

public class SequenceList {
    public static void main(String[] args) {
        SeqList seqList = new SeqList();
        System.out.println("插入元素按顺序排列:");
        seqList.insert(5);
        seqList.insert(6);
        seqList.insert(3);
        seqList.insert(1);
        seqList.insert(9);
        seqList.insert(7);
        seqList.insert(2);
        seqList.insert(10);
        seqList.tostring();
        System.out.println("删除指定位后的指定位元素:");
        seqList.delete(2,2);
        seqList.tostring();
    }
}

结果:

image.png

更新时间:
2019-5-8
12:25

上一篇 下一篇

猜你喜欢

热点阅读