zoukankan      html  css  js  c++  java
  • 1.线性顺序表

    线性结构概念:

    1.除了第一个和最后一个元素,每个元素都有一个前驱和一个后继元素

    2.第一个元素没有前驱

    3.最后一个元素没有后继

    操作:

    1.元素个数

    2.插入

    3.删除

    4.查找

    5.判断是否为空

    /**
    * 线性表接口
    */
    public interface List<E> {

    public int getSize();

    public boolean isEmpty();

    //插入元素
    public void add(E e);

    //对于位置添加元素
    public void add(int index,E e);

    public void delete(int index);

    public E get(int index);

    }

    计算机存储结构:顺序存储和离散存储

    顺序结构的线性表是顺序表

    顺序表实现类:

    public class SequenceList<E> implements List<E> {

    private final int DEFAULT_SIZE = 10;

    int maxSize;

    int currentSize;//當前長度

    private E[] emelents;//元素

    public SequenceList() {
    init(DEFAULT_SIZE);
    }

    public SequenceList(int size) {
    init(size);
    }

    private void init(int size) {
    this.maxSize = size;
    currentSize = 0;
    emelents = (E[])new Object[size];
    }


    @Override
    public int getSize() {
    return currentSize;
    }

    @Override
    public boolean isEmpty() {
    return currentSize == 0;
    }


    @Override
    public void add(int index, E e) {
    if(index<0||index>currentSize){
    throw new RuntimeException("參數錯誤");
    }
    for (int i = currentSize; i > index; i--) {//移動後面的元素
    emelents[i] = emelents[i-1];
    }
    emelents[index] = e;
    currentSize++;
    }

    @Override
    public void delete(int index) {
    if(isEmpty()){
    throw new RuntimeException("無法刪除");
    }else {
    if(index<0||index>currentSize-1){
    throw new RuntimeException("非法");
    }
    for (int i = index; i < currentSize ; i++) {
    emelents[i] = emelents[i+1];
    }
    currentSize--;
    }
    }

    @Override
    public E get(int index) {
    if(index<0||index>currentSize){
    throw new RuntimeException("");
    }
    return emelents[index];
    }
    }

    分析:插入和删除需要移动大量的元素,O(n)
    优点:支出随机访问,底层数组,内存连续,空间利用率高
    确定:大小固定,插入删除需要移动大量的数据


  • 相关阅读:
    51nod1711 平均数
    51nod1204 Parity
    51nod1274 最长递增路径
    51nod1403 有趣的堆栈
    51nod1364 最大字典序排列
    bzoj1857: [Scoi2010]传送带
    bzoj3224: Tyvj 1728 普通平衡树
    bzoj2396: 神奇的矩阵
    bzoj2428: [HAOI2006]均分数据
    splay入门
  • 原文地址:https://www.cnblogs.com/xu-xiang/p/10231827.html
Copyright © 2011-2022 走看看