01-Linear table (data structure and algorithm)

Main points:

  • program = data structure + algorithm

1. Overview of data structure

Program = data structure + algorithm

Data structures: the way computers store and organize data

Algorithms: Ways to Process Data

1.1 Basic Concepts and Terminology

1. Data

Data (data): all the symbols that can be input into the computer to describe objective things .

  • Numerical data : Indicates quantity, consisting of numbers, decimal points, plus and minus signs, and the letter E representing power. Numeric data cannot contain text and must be numeric

  • Non-numerical data : computer applications such as text, images, sounds, etc.

2. Data elements

Data element (data element): the basic unit of data , also known as node (node) or record (record)

3. Data object

Data object: A collection of data elements with the same characteristics, which is a subset of data .

  • Integer data object: a collection of all positive and negative integers, each of which is a data element

1.2 Classification of data structures

Traditionally, we can divide data structures into two categories: logical structures and physical structures :

  • Logical structure classification : Logical structure is a model abstracted from specific problems . It is a structure in an abstract sense. It is classified according to the relationship between data elements in objects. It is also a problem that we need to pay attention to and discuss in the following topics

    • Collection structure : In the collection structure, the data elements have no other relationship except that they belong to the same collection

    • Linear structure : There is a one-to-one relationship between data elements in a linear structure

    • Tree structure : There is a one-to-many hierarchical relationship between data elements in the tree structure

    • Graph structure : The data elements of the graph structure are many-to-many relationships

  • Physical structure classification : The real representation of the logical structure in the computer (also known as the image) is called the physical structure (actual storage structure), which can also be called the storage structure. Common physical structures include sequential storage structure and chain storage structure.
    • Sequential storage structure : Put data elements into storage units with continuous addresses , and the logical and physical relationships between the data are consistent. For example, our commonly used arrays are sequential storage structures.

    • Chained storage structure : store data elements in any storage unit, and this group of storage units can be continuous or discontinuous . At this time, data elements cannot reflect the logical relationship between elements, so a pointer is introduced in the chained storage structure to store the address of the data element, so that the location of the associated data element can be found through the address.

Second, the linear table

2.1 Overview of linear structures

1. A linear list is a typical linear structure : there is one and only one start node and one terminal node , and all nodes have at most one direct predecessor and one direct successor .

2. Linear structure expression : (a1, a2, a3, ... , ai)

3. Linear structure features :

  • There is only one first node and one last node

  • Except for the first and last nodes, other nodes have only one direct predecessor and one direct successor

In short, the linear structure reflects that the logical relationship between nodes is one-to-one .

4. Linear structures include linear lists, stacks, queues, strings, arrays, etc.

A linear table is the most basic, simplest, and most commonly used data structure. A linear list is a finite sequence of n data elements with the same properties.

If the linear table is defined in mathematical language, it can be expressed as (a1,...ai-1,ai,ai+1,...an), ai-1 is ahead of ai, ai is ahead of ai+1, We call ai-1 the predecessor element of ai , and ai+1 the successor element of ai .

The data storage method in the linear table can be sequential storage or linked storage. According to the different data storage methods, the linear table can be divided into sequential table and linked list .

Basic operations of linear tables: initialization, value, lookup, insertion, deletion.

The sequential table is a linear table stored in the form of an array in the computer   memory . The sequential storage of the linear table refers to using a group of storage units with continuous addresses to store each element in the linear table in sequence.

typedef int ElemType;
typedef unsigned int uint;
typedef struct{
    ElemType *elem;  //顺序表中存储数据的空间
    uint length;     //当前存储数据的个数
    uint listSize;   //顺序表的容量,最多可以存储的元素的个数
}SqList;

2.2 Initialization sequence table

logic:

  • Allocate space for pointers to store data

  • The sequence table length is initialized to 0

  • The capacity of the sequence table is the allocated space  sizeof (ElemType)

/*
 * @brief  初始化顺序表
 * @param listSize 顺序表容量
 * @return 返回初始化好的顺序表
 * */
SqList SqList_init(uint listSize){
    //为线性表存储数据分配空间
    SqList t;
    t.elem = (ElemType *)malloc(listSize*sizeof(ElemType));
    t.length = 0;
    t.listSize = listSize;
    return t;
}

2.3 Output of sequence table

logic:

  • Traverse the entire sequence table according to the length of the sequence table

  • Output each data element traversed

/*
 * @brief 打印顺序表的所有的元素
 * @param t 需要输出的顺序表
 * @return void
 * */
void print_SqList(SqList t){
    printf("SqList print: ");
    int i;
    for (i = 0; i < t.length; i++){
        printf("SqList_data, %d", t.elem[i]);
    printf("\n");
    }
}

2.4 The value of the sequence table

logic:

  • Determine whether the subscript of the element to be obtained is legal

  • Returns an error number if invalid

  • If legal, directly return the element corresponding to the subscript

/*
 * @brief 获取顺序表中某个位置的元素
 * @param t 需要操作的顺序表
 * @param index 需要获取的元素的位置/下标
 * @return ElemType 获取到的元素
 * */
ElemType get_elem(SqList t, uint index){
    if (index >= t.length){
        printf("index out of range \n");
        return -1;
    }
    return t.elem[index];
}

2.5 Search for sequence table elements

logic:

  • Traverse the entire sequence table by the length of the sequence table

  • Compare the traversed elements with the elements to be found, if they are not equal, continue to traverse backwards

  • If equal, stop traversal and exit the loop

  • Returns the subscript of the element traversed

/* @brief 在顺序表中查找指定的元素
 * @param t 需要操作的顺序表
 * @param elem 需要查找的元素
 * @return int 成功返回值元素的下标,失败返回-1
 * */
int find_elem(SqList t, ElemType elem){
    int index = -1;  //保存元素的下标,默认需要查找的元素不在顺序表中
    //遍历整个顺序表
    int i;
    for (i = 0; i < t.length; i++){
        if (t.elem[i] == elem){
            index = i;
            break;
        }
    }
    
    if (-1 == index)
        printf("Can not find element : %d\n", elem);
    return index;
}

2.6 Destruction of sequence table

logic:

  • Frees space allocated on the heap when initializing the sequence table

  • Set the length of the sequence table to 0

  • Set the capacity of the sequence table to 0

/*
 * @brief 销毁一个顺序表
 * @param t 需要销毁的顺序表指针
 * */
int SqList_destroy(SqList *t){
    if (NULL == t)
        return error;
    if (t->elem != NULL){
        free(t -> elem);
        t->length = 0;
        t->listSize = 0;
    }
    return success;
}

2.7 Delete the element at the specified position

logic:

  • Determine whether the subscript of the element to be deleted is legal, and return an error code if it is not legal

  • Move the elements from i+1 to length-1 (the subscript of the last element) one position forward

  • Sequence table length -1

/*
 * @brief 删除指定位置的元素
 * @param t 需要操作的顺序表指针
 * @param index 需要删除的元素的下标
 * */
int locate_elem_delete(SqList *t, uint index){
    if (NULL == t)
        return error;
    if (index >= t->length){
        printf("index out of range ...\n");
        return error;
    }
    int i;
    //删除第index个节点,后面的数据移动 t->length - (index + 1)次
    //将第index+1开始到第t.length-1位置的元素往前移动
    for (i=0; i < t->length - (index + 1); i++){
        t->elem[index+i] = t->elem[index+i+1];
    }
    t->length--;
    return success;
}

2.8 Delete the specified element

logic:

  • traverse the entire sequence table

  • Determine whether the traversed element is an element that needs to be deleted, if not, continue to traverse backwards

  • If they are equal, move all elements behind the element forward by one position

/*
 * @brief 将顺序表中指定的元素删除
 * @param t 需要操作的顺序表指针
 * @param elem 需要删除的元素
 * @return 成功返回OK,失败返回error
 * */
int delete_designated_elem(SqList *t, ElemType elem){
    if (NULL == t){
        printf("[%s %d] SqList is NULL\n", __FUNCTION__ , __LINE__);
        return error;
    }
    
    int i = 0;
    while (i != t->length){
        //先找到需要删除的元素
        if (t->elem[i] != elem){
            i++;
            continue;
        }
        //记录其位置
        int p = i;
        int j;
        //将后面的元素往前移动一个位置
        for (j = 0; j < t->length - (p + 1); j++){
            //将第index + i + 1个元素 覆盖掉第 index + i个元素
            t->elem[p + j] = t->elem[p + j + 1];
        }
        t->length--;
    }
    return success;
}

2.9 Expansion of the sequence table

logic:

  • Expand the capacity of the sequence table to twice the original size

/*
 * @brief 为顺序表扩容
 * @param t 需要扩容的顺序表指针
 * @return 成功返回success, 失败返回error
 * */
int SqList_expand(SqList *t){
    if (NULL == t){
        printf("[%s %d] SqList is NULL \n", __FUNCTION__ , __LINE__);
        return error;
    }
    //为顺序表分配新的空间
    t->listSize *= 2;
    t->elem = (ElemType *)realloc(t->elem, t->listSize * sizeof(ElemType));
    return success;
}

2.10 Insert an element before the specified position

logic:

  • Determine whether the insertion position is legal

  • Determine whether the sequence table is full, and expand if it is full

  • Calculate the number/times of elements that need to be moved according to the inserted position

  • Move all elements starting from the specified position backward by one position as a whole (starting from the last position and moving backward)

  • Place the element to be inserted at the inserted position

  • Sequence table length +1

/*
 * @brief 在指定位置的前面插入一个元素
 * @param t 需要操作的顺序表指针
 * @param index 需要插入的位置
 * @param elem 需要插入的元素
 * @return error 成功返回success, 失败返回error
 * */
int elem_insert(SqList *t, uint index, ElemType elem){
    if (NULL == t){
        printf("[%s %d] SqList is NULL \n", __FUNCTION__ , __LINE__);
        return error;
    }
    //判断插入的位置是否合法
    if (index > t->length)
        return error;
    //判断顺序表是否满了,如果满了则扩容
    if (t->length == t->listSize){
        SqList_expand(t);
        print_SqList(*t);
    }
    int i;
    for (i = 0; i < t->length - index; i++){
        //从最后一个元素开始移动
        t->elem[t->length+i] = t->elem[t->length-1+i];
    }
    //将需要插入的元素放置到插入的位置
    t->elem[index] = elem;
    t->length++;
    return success;
}

2.11 Time Complexity of Sequence List

1. Get the time complexity of elements

Because the element at the corresponding position can be obtained directly through the subscript method, because no matter how long the sequence table is, it only needs to be accessed once to obtain the element, so the time complexity is O(1 )

2. Time complexity of inserting elements

For each insertion, the element behind the corresponding position needs to be moved once. As the number of elements N increases, more elements are moved, and the time complexity is O(n)

3. Time complexity of deleting elements

Every time you delete, you need to move the elements behind the corresponding position once. As the amount of data N increases, more elements are moved, and the time complexity is O(n)

 

Guess you like

Origin blog.csdn.net/March_A/article/details/131647949