Detailed explanation of data structures and algorithms Arrays and linked lists

Basic characteristics of arrays

Array is a commonly used data structure. He created a series of memory spaces in memory to save data. Access to his data can be done directly through subscripts.

However, because the memory address of each element of the array is clear, adding or deleting elements in the array is usually accompanied by the overall forward or backward movement of the subsequent elements. For example, to delete the 0th bit of the array from the array, move each subsequent bit forward to one bit.

Moreover, the size of the array was determined when it was created. If you want to expand the capacity, you must find the continuous memory address of the new capacity in the memory, copy the original data to the new memory, and there are higher cost.

The linked list is the data structure used to solve these shortcomings.

Basic characteristics of linked lists

The elements of the linked list are discrete in the memory space, and the order of their elements is to save the address pointing to the next node through the previous node, thus forming a dynamic collection.

Let's look at a simple linked list implementation based on the Java language:

public class SimpleNode<T> {
    public T value;
    public SimpleNode<T> next;
}

Are you surprised? In fact, this is the simplest implementation of the linked list. If you add in the object

public SimpleNode<T> prep;

Field, this becomes a doubly linked list.

The advantage of the linked list is that when adding and deleting data, you can only modify the prep and next attributes of the node at the addition point, and you can achieve the goal without having to modify too many nodes.

Comparison of arrays and linked lists

Array Linked list
Memory usage Relatively small Relatively large, with additional memory overhead
Access the specified subscript element Direct access to o (1) time complexity To search backward from the first node, the time complexity is o (n)
Add elements to the specified subscript o (n) time complexity, it takes a long time to add in the first position of the array o (n) time complexity, adding to the middle of the array needs to find the node before doing subsequent operations
Delete element to specified subscript Basically the same as above Basically the same as above
Published 19 original articles · praised 8 · visits 4041

Guess you like

Origin blog.csdn.net/u014068277/article/details/103229643