Data structure: Detailed graphic and text explanation of various operations of sequence tables (adding elements, finding elements, deleting elements, assigning values to elements at specified positions)


 Table of contents

1. The concept of sequence list

2. Implementation of sequence table

Add new element

Added at the end by default

Add element at specified position

Find element

Find if exists

Find the position corresponding to the element

Find the element corresponding to the specified position

Delete element

Get sequence table length

Clear sequence list


1. The concept of sequence list

In linear data structures, we generally divide them into two categories: sequential lists and linked lists.

        A sequence table is a linear data structure in which data elements are stored in linear order, usually implemented using an array. The elements in the sequence table are arranged in a certain order, and each element can be accessed through subscripts. Sequential tables support random access and can quickly access any element, but when inserting or deleting elements, the remaining elements need to be moved, which is less efficient. The sequence table is a continuous storage area in the memory, and the data elements are stored closely adjacent to each other, so random access is fast. Since the capacity of the sequence table is fixed, memory space needs to be reallocated when the number of elements exceeds the capacity, which may lead to time-consuming operations and an increase in memory usage.

2. Implementation of sequence table

A sequence table is a data structure that has nothing to do with language syntax. Languages ​​just describe this data structure in different ways.

To give a popular example, if there is a rockery on the lake, and there are a group of tourists by the lake

Some people say in English “There is a rockery on the lake”

Some people said in Chinese “There is a rockery on the lake”

Japanese translation for people with knowledge “There is an artificial mountain on the surface of the lake”

And this rockery is like our data structure, and the English, Chinese, and Japanese we use are our different programming languages. Therefore, in the process of learning data structures, we do not have to deliberately care about the language and grammar used. What we need to understand is the essence, functions and characteristics of this data structure. The author here uses Java as the carrier of the sequence table to share.

We usually use numerical values ​​to implement sequence tables. For a sequence table, it should have at least the following two member variables:

  • Array: used to store data and elements
  • The number of elements stored in the array: recording the number of elements in the array can facilitate us to perform operations such as adding and deleting better
public class MyArrayList{
    public int[] arr;//存放数据的数组
    public int usedSize;//记录数组内元素的个数
}

For a sequence table, it should implement the following functions. We abstract the unique functions and characteristics of these sequence tables into an interface, and then use code to implement a real sequence table.

public interface Ilist {
    // 新增元素,默认在数组最后新增
    public void add(int data);
    // 在 pos 位置新增元素
    public void add(int pos, int data);
    // 判定是否包含某个元素
    public boolean contains(int toFind);
    // 查找某个元素对应的位置
    public int indexOf(int toFind);
    // 获取 pos 位置的元素
    public int get(int pos);
    // 给 pos 位置的元素设为 value
    public void set(int pos, int value);
    // 删除第一次出现的关键字key
    public void remove(int toRemove);
    // 获取顺序表长度
    public int size();
    // 清空顺序表
    public void clear();
}

Add new element

We divide new elements into two ways:default tail new element and specified Add new element at position

Added at the end by default

At the beginning, the array size is the default size we set5. There are no elements inside the array, which means the default The number of elements is also 0, we can add elements directly; however, the content of the array is limited. When the array content is full, it needs to be expanded. We use copyOf< a i=4> Directly double the size of the original array, and then let this array receive the expanded array again.

Come to the specific new element section,usedSize is equivalent to always recording the last element of the sequence list, directly to the last element of the current sequence list Place datadata into one position, and add one to the number of recorded elements.

public static final int DEFAULT_SIZE = 5;
    // 新增元素,默认在数组最后新增
    public void add(int data) {
        //判断满了之后要扩容
        if (arr.length == usedSize) {
            arr = Arrays.copyOf(arr, DEFAULT_SIZE * 2);
        }
        arr[usedSize] = data;
        usedSize++;
    }

Add element at specified position

Before adding, judge the position to be added. In the sequence table, every node except the first node has its predecessor, so we have to make sure that the position to be added is in the sequence. If it is not in the sequence, we Throw a custom exception (this step is not required)

After confirming that the input position is legal, you must first determine whether the sequence table is full. If it is full, expand it. If there is sufficient remaining space, add it. When adding, you need to Move the elements to make room for the new elements, and then put the elements we want to put in the vacant positions. When we complete the addition, record the number of elementsusedSizeOf course we have to add one

Code:

    private void cheakPos(int pos) {
        if (pos < 0 || pos > usedSize)
            throw new ExceptionOfPos("pos位置不能为:" + pos);
    }    
    public void add(int pos, int data) {
        cheakPos(pos);
        //判断满了之后要扩容
        if (arr.length == usedSize) {
            arr = Arrays.copyOf(arr, DEFAULT_SIZE * 2);
        }
        //移动元素留出空位
        for (int i = usedSize - 1; i >= pos; i--) {
            arr[i + 1] = arr[i];
        }
        arr[pos] = arr[pos - 1];
        //给pos位置元素赋值
        arr[pos - 1] = data;
        usedSize++;
    }
public class ExceptionOfPos extends RuntimeException{
    public ExceptionOfPos(String message) {
        super(message);
    }
}

Find element

Search can be divided into

  • Find if exists
  • Find the position corresponding to the element
  • Find the element corresponding to the specified position

Find if exists

search is the best to implement, because we have not changed the content of the sequence table, which is also the biggest advantage of the sequence table. The search only needs to traverse one by one to see if there is the element we are looking for. If there is, return existence(true), if not, return non-exist< /span>(false)

    // 判定是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if (arr[i] == toFind)
                return true;
        }
        return false;
    }

Find the position corresponding to the element

Traverse one by one to see if there is the element we are looking for. If there is, return the subscript of the element. If not, return-1

    // 查找某个元素对应的位置
    public int indexOf(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if (arr[i] == toFind)
                return i + 1;
        }
        return -1;
    }

Find the element corresponding to the specified position

After determining the legality of the input position and sequence table (it does not necessarily have to throw an exception, the author just gives an idea here), just return the element at the target position directly.

    // 获取 pos 位置的元素
    public int get(int pos) {
        //检查输入位置是否合法
        cheakPos(pos);
        //检查顺序表是否为空
        cheakEmpty();
        return arr[pos];
    }

    private void cheakPos(int pos) {
        if (pos < 0 || pos > usedSize)
            throw new ExceptionOfPos("pos位置不能为:" + pos);
    }
    
    private void cheakEmpty() {
        if (usedSize == 0)
            throw new ExceptionOfEmpty("当前顺序表为空,无法操作");
    }

Delete element

Before deleting, you must first determine whether the sequence table is empty. If it is not empty, we use the search method just writtenindexOf Just find the position of the element to be deleted, and then overwrite the elements in sequence from back to front. Because there is no element behind the last element, we have to manually overwrite it. After the elements are reduced, the corresponding number of records also needs to be reduced by oneusedSize

    //删除第一次出现的关键字key
    public void remove(int toRemove) {
        //检查顺序表是否为空
        cheakEmpty();
        int delPos = indexOf(toRemove);
        for (int i = delPos; i < usedSize; i++) {
            arr[i-1] = arr[i];
        }
        arr[usedSize-1] = arr[usedSize];
        usedSize--;
    }

Get sequence table length

BecauseusedSize saves the number of sequence table elements, which is the length of the sequence table, so directly after judging that the sequence table is not empty Just returnusedSize

    // 获取顺序表长度
    public int size() {
        //检查顺序表是否为空
        cheakEmpty();
        return usedSize;
    }

Clear sequence list

Set the number of elements to 0 directly, and other methods cannot operate the sequence table throughusedSize, and you are done. Clearing the sequence table

    // 清空顺序表
    public void clear() {
        usedSize = 0;
    }



  That’s it for this sharing. I hope my sharing can be helpful to you. I also welcome everyone’s support. Your likes are the biggest motivation for bloggers to update! If you have different opinions, you are welcome to actively discuss and exchange in the comment area, let us learn and make progress together! If you have relevant questions, you can also send a private message to the blogger. The comment area and private messages will be carefully checked. See you next time

Supongo que te gusta

Origin blog.csdn.net/m0_69519887/article/details/134712582
Recomendado
Clasificación