Basic concepts of linear tables

Source: Internet
Author: User
Tags array length rand
definition of a linear table

linear table: A finite sequence of 0 or more data elements.

A few key places.
First, it's a sequence. In other words, there is a sequence between elements, if there are more than one element, then the first element has no predecessor, the last element has no successor, each other element has only a precursor and successor.

Then, the linear table emphasis is limited. In fact, the objects in the computer are limited, the infinite number of sequences, only in the concept of mathematics.

If you use mathematical language to define. Can be as follows:
if the linear symbol (A1,...,ai-1,ai,ai+1,...,an), then the table ai-1 ahead of the Ai,ai leader in Ai+1, said Ai-1 is the direct precursor of AI, Ai+1 is the direct successor of the AI elements. When i = 1,2,...,n-1, Ai has and has only a direct successor, when i = 2, 3, ..., n, the AI has and has only a direct precursor.

So the number n (n≥0) of the linear table element is defined as the linear table length, and when N=0 is called an empty table.

Each data element in a non-empty table has a definite position, such as A1 is the first Data element, an is the last data element, AI is the first data element, and I is the bit order of the data element AI in the linear table.

Give a few examples to determine whether a linear table.
The first one: the constellation List of the year, is not a linear table.

A: Of course, the constellation is usually the beginning of Aries, Pisces end, the constellation has a precursor successor, and a total of 12, so fully conform to the definition of linear table.

Second: The company's organizational coitus, the general manager of the management of several directors, each director of the management of several managers, each manager to manage their respective following and staff. Is this organizational structure a linear relationship?

Answer: No, why not. Because each element has more than one successor, it is not a linear table.

The third: The friendship between the class students, is not a linear table it.

A: No, because everyone can build friendships with a number of classmates and not meet the linear definition.

Fourth: The class of the student's point roster, is not a linear table. is not the DOT roster.

Answer: Yes, this and just the friendship is completely different, because it is a finite sequence, but also meet the same characteristics of the same type, the point of the roster, each element in addition to the student's study, but also can have the name of the classmate, sex, birth dates and so on, this is actually our previous data items. In a more complex linear table, a data element can consist of several data items. abstract data types of linear tables

The abstract data type of a linear table is defined as follows:

The data object collection for the ADT linear table (list)
    linear table is {A1,A2,...., an}, and each element type is datatype. In addition to the first element A1, each element is known and has only one direct precursor element, except the last element an, each element is known and has only one immediate successor element. The relationship between data elements is one-to-one.

Operation
    Initlist (*L): Initialize the operation to create an empty linear table.
    Listempty (L): Returns True if the linear table is NULL, otherwise returns FALSE.
    clearlist (*l): Linear table empty.
    Getelem (l,i,*e): Returns the first position element in the linear table L to E.
    Locateelem (l,e): Finds an element in linear table L that is equal to the given value E,
        returns the sequence number of the element in the table if the lookup succeeds, or returns 0 to indicate failure.
    Listinsert (*l,i,e): Inserts the element e in the first position of the linear table.
    Listdelete (*l,i,*e): Deletes the first element of the linear table L and returns its value
    with E Listlength (L): Returns the number of elements in the linear table L.

For different applications, the operation of the linear table is different, the above operation is the most basic, the problem of the design of the linear table more complex operations, can be used in combination of these basic operations to achieve.

For example, to implement the set of two linear tables set A and B operations. That is to make the set a = A∪b, to put it plainly, is to insert the data elements that exist in set B but do not exist into a.

With a careful analysis of this operation, we find that we just loop through the elements in set B to determine if there is a, and if it does not, insert it into a. Ideas should be very easy to think of.

Let's say that La represents a collection a,lb represents a set B, the implementation code is as follows:

Insert all elements in the online table lb, but not in LA, into La
void unionl (list *la, list Lb)
{
    int la_len,lb_len,i;
    Elemtype e;
    La_len = Listlength (*la);
    Lb_len = Listlength (*lb);
    for (i = 0; i≤lb;i++)
    {
        Getelem (lb,i,*e);//Remove the first Data element of Lb to assign to E
        if (! Locateelem (*la,e))//la does not exist with the same data element
        {
            Listinsert (la,++la_len,e) as the E element;/insert
        }
}}

Here we for the union operation, used in front of the linear table basic operations Listlength, Getelem, locateelem,listlength, etc., visible, for complex personalized operation, in fact, is the basic operation of the combination to achieve. sequential storage structure of linear table 1. Sequential Storage definition

Having said so many linear tables, we look at the physical structure of the linear table, the first-order storage structure.

The sequential storage structure of a linear table, specifying a data element that stores a linear table at a time with successive storage cells of the address. 2. Sequential storage mode

The order of the linear table storage way, plainly, is in the memory to find a place, put a certain amount of memory space, and then the same data types of data elements exist in the inside. Since the data elements of the linear table are of the same type, a one-dimensional array of C language is used to implement the sequential storage structure , that is, the first data element is stored in the position of the array table 0, and then the adjacent elements of the linear table are stored in the adjacent position in the array.

In order to create a linear table, to find a piece of land in memory, so the first position of this piece of land is very critical, it is the starting position of storage space.

In a linear table, we estimate the maximum storage capacity of this linear table, and build an array, the length of which is the maximum storage capacity.

We already have the starting position and the maximum capacity, so we can add data to it. As the data is inserted, the length of our linear table becomes larger, but the current length of the linear table cannot exceed the storage capacity, that is, the length of the array.

See the linear table in order to store the structure code.

#define MAXSIZE 20//Storage space initial allocation
 typedef int ELEMTYPE;//ELEMTYPE Based on the actual situation, this assumes the int
 typedef struct
 {
     Elemtype data[maxsize];//Array stores data elements, the maximum is MAXSIZE
     int length;//Linear table current length
 }sqlist;

Here we find that the description of the sequential storage structure requires three attributes :
the starting position of the ① storage space : array data, where storage space is stored.

maximum storage capacity of ② linear table : array length maxsize.

the current length of the ③ linear table : length. 3. The length of the array differs from the linear table length

The length of the array is the length of the storage space that holds the linear table, and the storage space is usually unchanged after allocation .

The linear table length is the number of element data in the linear table, and as the linear table inserts and deletes the operation, this quantity is changed .

At any time, the length of the linear table should be less than or equal to the length of the array. 4. Address Calculation method

The starting point of the linear table begins with 1, but the array is the first subscript from 0, and then the i-1 of the linear table is stored in the position of the array labeled as a.

Storing a sequential table with an array means allocating fixed-length array space, so the allocated array space is greater than or equal to the current linear table because it can be inserted and deleted in the linear table.

Because each data element, whether he is integral, solid or character, it needs to occupy a certain amount of storage space. Assuming that a C storage unit is occupied, the storage location of the 1 elements in the linear table and the storage location of the I data element satisfy the following relationships (Loc represents the function that obtains the storage location).

LOC (ai+1) = LOC (AI) + C

So the storage location for the AI of the first Data element can be inferred from A1:

LOC (AI) = LOC (AI) + (i-1) * C

with this formula, you can always calculate the address of any position in the linear table, whether he is the first or the last, is the same event. So the data we put in or out of each linear table is equal to the time for the computer, that is, a constant, so the concept of the time complexity that we have learned in the algorithm, the performance of its access Time is O (1). We usually refer to a storage structure with this feature as a random access structure. iv. insertion and deletion of sequential storage structure 1. Get element Operations

For the sequential storage structure of the linear table, it is very simple to implement the Getelem operation and return the first position element in the linear table L. As far as the program is concerned, as long as the first element is within the subscript range, the i-1 of the array is returned to the following table values.
Look at the code:

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
Status is the type of function whose value is the function result status code, such as OK
//Initial condition: sequential linear table L already exists, 1≤i≤listlength (L)
//Action Result: Returns the value of the first element in L with e
Getelem (sqlist l,int i,elemtype *e)
{
    if (l.length = 0 | | I < 1 | | | i > l.length) return
        ERROR;
    *e = l.data[i-1];
    return OK;
}

Note that here the return value type status is an integral type, and returns OK on behalf of 1,error 0. 2. Insert Operation

As we have just mentioned, the time complexity here is O (1). Let's consider how to do this if we are going to implement Listinsert (*l,i,e), that is, inserting the new element E in the first position in the linear table L.

the idea of inserting algorithm :

If the insertion position is unreasonable, throw an exception ;

throws an exception or dynamically increases capacity if the linear table length is greater than or equal to the length of the array ;

The ③ moves forward from the last element to the first element, moving them back one at a while;

will insert the element to fill in position I ;

table length plus 1.
The implementation code is as follows:

Initial conditions: Sequential linear table L already exists, 1≤i≤listlength (L)
//Action Result: Inserts the new data element E,l's length in the L position and adds 1
Status listinsert (sqlist *l,int I, Elemtype e)
{
    int k;
    if (l->length = = MAXSIZE)//When the linear table is full return
        ERROR;
    if (I < 1 | | | I >l->length + 1)//When I is not in range
    {return
        ERROR;
    }
    if (i <= l->length)//If Insert data position is not footer
    {for
        (k = l->length-1;k > i-1;k--)
        {
            l->data[k + 1] = l->data[k];
        }
    }
    L->DATA[I-1] = e;//Inserts a new element into
    l->length++;
    return OK;
}
3. Delete Operation

The idea of removing algorithms:
If the deletion position is unreasonable, throw an exception ;

Remove the deletion element ;

The ③ moves from the location of the deletion element to the last element position, moving them one position forward, respectively ;

table length minus 1.

The implementation code is as follows:

Initial conditions: Sequential linear table L already exists, 1 <= i <= listlength (l)
//action result: Delete l element I, and return its value with E, L's length minus 1
Status listdelete (sqlist *l, int I, Elemtype *e)
{
    int k;
    if (L->length = = 0)//linear table is null return
        ERROR;
    if (I < 1 | | | i > l->length)//delete location incorrect return
        ERROR;
    *e = l->data[i];
    if (i < l->length)
    {for
        (k = i;k < l->length;k++)
            l->data[k-1] = l->data[k];
    }
    l->length--;
    return OK;
}

Now, let's analyze the complexity of the events that are inserted and deleted.
Now let's look at the best case , if an element is to be inserted in the last position, or if the last position is deleted, the time complexity is O (1), because no elements need to be moved.

At worst , if the element is to be inserted into the first position or delete the first element, what is the complexity of the time? That means that all elements are backwards or forwards, so this time complexity is O (n).

As for the average case, because the element inserts to the first position, or deletes the first element, needs to move the n-i element, each position inserts or deletes the element the likelihood is the same, is the position leans forward, moves the element many, after the position, moves the element to be few. The final average number of moves is the same as that of the most intermediate element (n-1)/2.

According to the derivation of time complexity, the average time complexity is still O (n).

This explains the description. The sequential storage structure of a linear table, in which data is stored and read, regardless of the location, the time complexity is O (1), and when inserted or deleted, the time complexity is O (n). This shows that it is more suitable for the number of elements is not very different, but more access to data applications . 4 The advantages and disadvantages of the sequential storage structure of linear table

Advantages
need not add extra storage space for logical relationships between elements in a table

can quickly access elements in any location in a table

Disadvantage
inserts and deletes need to move a large number of elements

It is difficult to determine the capacity of storage space when the linear table length changes greatly.

creates "fragmentation" of storage space . chain-type storage structure of linear table 1. Linear chain-Link storage structure definition

The chain storage structure of a linear table is characterized by storing the data elements of a linear table in a group of storage units, which can be continuous or discontinuous. This means that these elements can exist in any location where memory is not occupied.

Previously in a sequential structure, each element data needed to store only the data element information. Now in the chain structure, in addition to the data element information to be stored, it also stores the storage address of its successor element.

Therefore, in order to represent the logical relationship between the AI of each data element and its direct back-level element ai+1, the data element AI, in addition to storing its own information, also needs to store an indication of its immediate successor (i.e. the direct successor storage location). The domain that stores data element information is called the data domain, and the domain where the immediate successor is stored is referred to as the pointer field. The information stored in the pointer field is called a pointer or chain. These two pieces of information form the storage image of the data element AI, known as node (node).

N nodes (Ai's storage image) chain form a linked list, which is a chain-type storage structure for the linear table (A1,a2,...., an), because each node in the list contains only one pointer field, so it is called a single linked list . It is through the pointer field of each node that the single linked list links the data elements of the linear table in their logical order.

For a linear table, there must be a tail, and the list is no exception. The storage location of the first node in the list is called the head pointer, so the entire list must be accessed from the beginning. Each subsequent node, in fact, is the position that the previous successor pointer points to.

The last one, of course, means that the immediate successor does not exist, so we stipulate that the last node pointer of the linear list is "null" (usually represented by a null or "^" symbol).

Sometimes, in order to more easily operate the linked list, we will have a node in front of the first node of the single linked list, called the head node . The data field of the head node can store no information, or it can save additional information such as the length of the linear table, and the pointer field of the head node stores the pointer to the first node. 2. The similarities and differences between the head pointer and the head node

The similarities and differences of the head and head nodes.
Head pointer
The ① head pointer is a pointer to the first node of the linked list, and a pointer to the head node if the linked list has a head node.

The ② head pointer has the function of marking, so the common head pointer is the name of the list.

③ the header pointer is not empty, regardless of whether the linked list is empty. The head pointer is an essential element of a linked list.

Head knot.
The ① head node is established for the unification and convenience of operation, and it is placed between the nodes of the first element and its data field is generally meaningless.

② has a head node and inserts a node before the first element node, and its operation is unified with the other nodes.

The ③ head node is not necessarily the essential element of the chain list. 3. Linear chain table type storage structure Code description

If the linear list is an empty table, the pointer field of the header node is "null".

In a single linked list, we can use the structure pointers in C to describe them.

Single-chain table storage structure of linear table
typedef struct NODE
{
    elemtype data;
    struct Node *next;
} Node;
typedef struct NODE *linklist;//definition linklist

In this structure definition, we also know that nodes consist of data fields that hold data elements and pointer fields that store subsequent node addresses. Suppose P is a pointer to the first element of the linear table, then the data field of the node AI can be represented by P->data, the P->data value is a data element, and the pointer of the node AI can be represented by P->next,p-> The value of next is a pointer. Who is p->next pointing to? Of course it points to the first 1 elements, which point to ai+1. That is to say P->data = AI, then p->next->data=ai+1 six, single linked table reading

In the sequential storage structure of a linear table, it is easy to compute the storage location of any one element. But in a single list, because of where the first element is. There is no way to know from the beginning, you must start from scratch. Therefore, for the single linked list to obtain the first element of the operation Getelem, in the algorithm, relatively troublesome.

To obtain the first data of the list of the algorithm thinking:
1. Declare a pointer p to point to the first node of the list, and initialize J starting from 1.
2. When J < I, the link list is traversed so that the pointer of P moves backwards, pointing continuously to the next node, j is cumulative 1;
3. If the end of the list P is empty, then the first node does not exist;
4. Otherwise find success, return the data of node p.
The implementation code is as follows:

Initial condition: Sequential linear table L already exists, 1≤i≤listlength (L)
//Action Result: Returns the value of the first Data element in L with e
(linklist l,int i,elemtype *e)
{
    int J;
    Linklist p;//declares a pointer
    p = l->next;//Let P point to the first node of the list L
    (j = 1;//j for the counter while
    (P && J < i)/ P is not null and the counter J is not equal to I, the loop continues
    {
        p = p->next;//Let P point to the lower node
        ++j;
    }
    if (P | | j > i) return
        error;//The first node does not exist
    *e = p->data;//Fetch the data return OK of the first node
    ;
}

To be frank, it is to start from scratch until the first node. Because the complexity of this algorithm depends on the position of I, when i = 1 o'clock, the variable is not required, and when i = n the traversal of the n-1 time is possible. So the worst case time complexity is O (n).

Because the structure of a single linked list does not define the table length, it is not convenient to use a for to control loops because it does not know how many times to cycle beforehand. The main idea is to "move the work pointer back", which is a common technique in many algorithms. viii. insertion and deletion of single linked list 1. Single-linked list insertion

Assuming that the node of the storage element e is S, the logical relationship between the nodes P, P->next and S will be changed, and the s must be inserted between the node P and the P->next.
There is no need to disturb other nodes, just let s->next and p->next pointers do a little bit of change.

The following two sentences are not commutative order
S->next = p->next;
P->next = s;

The algorithm idea of inserting the node in the single chain Table I data:
1. Declare a pointer p to point to the Link header node, initialize J starting from 1;
2. When J < I, we go through the list, let P's pointer move backwards, and point to the next node, J add 1
3. If the end of the list p is null, then the first node does not exist;
4. If the search succeeds, generate an empty node s in the system;
5. Assign the data element E to s->data;
6. Single linked list Insert standard statement s->next = p->next; P->next = s;
7. Return to Success

The implementation code algorithm is as follows:

Initial condition: Sequential linear table L already exists, 1≤i≤listlength (L)
//Operation result: Inserts a new data element before the L-I node position, the length of L is added 1
Status listinsert (linklist *l, int i , Elemtype e)
{
    int j = 1;
    Linklist p,s;
    p = *l;
    while (P && J < i)//looking for the first node
    {
        p = p->next;
        ++j;
    }
    if (!p | | J > 1)
    {return
        error;//I node does not exist
    }
    s = (linklist) malloc (sizeof (Node));//Generate new node
    s >data = e;
    S->next = p->next;//Assigns a subsequent node of P to the successor of s
    p->next = s;//The successor return OK assigned S to P
    ;

In this algorithm code, we use the C language malloc standard function, its function is to generate a new node, its type and node is the same, its essence is in memory to open up a space, with the storage of data e s node. 2. Single Linked list deletion

Now let's look at the deletion of the single linked list. Set the storage element AI node for q, to achieve the node Q delete single linked list of operations, in fact, it is the previous node of the pointer bypass, point to his successor node can be.

What we have to do, in fact, is a step, P->next = P->next->next, with Q to replace the P->next is:

Q = p->next;
P->next = q->next;

In other words, the subsequent node of P is changed to the subsequent subsequent node of P.

The algorithm idea of deleting node in single chain Table I data:
1. Declare a pointer p to point to the chain header pointer, initialize J starting from 1;
2. When J < I, we traverse the list, let the pointer of P move backwards, point to the next node continuously, I add 1;
3. If the end of the list p is null, then the first node does not exist;
4. Otherwise find success, will want to delete the node p->next assigned to Q;
5. Single linked list deletion standard and p->next = q->next;
6. Assign the data in the Q node to e as a return;
7. Release Q node
8. Return to Success

The implementation code algorithm is as follows:

Initial condition: Sequential linear table L already exists, 1≤i≤listlength (L)
//operation result: Delete L node of I and return its value with E, L's length minus 1
Status listdelete (linklist *l,int I, Elemtype *e)
{
    int J;
    Link p,q;
    p = *l;
    j = 1;
    while (P->next && J < i)/traversal looks for the i-1 node
    {
        p = p->next;
        ++j;
    }
    if (!) ( P->next) | | J > I) return
        error;//No. I node does not exist
    q = p->next;
    P->next = q->next;//assigns Q's successor to P's successor
    *e = q->data;//the data in Q node to e
    free (q); Let the system reclaim this node and release the memory return
    OK ;
}

The analysis of the single linked list insertion and deletion algorithm we have just explained, we found that they are in fact composed of two parts: the first part is to traverse to find the first node; the second part is inserting and deleting nodes.

From the whole algorithm, it is easy to deduce that their time complexity is all O (n).
If we do not know the position of the pointer of the first node, the single linked list data structure does not have much advantage over the insertion and deletion operation, and the offline sequential storage structure. If, however, we want to insert 10 nodes from position I, for the sequential structure it means that each n-i node is moved every time, O (n). and a single linked list, we just have to find the pointer to position I at the first time, O (n), then simply move the pointer through the assignment, and the event complexity is O (1).
Obviously, the more frequent operation of inserting and deleting data, the more obvious the advantage of a single linked list . eight, single linked list of the whole table creation

The creation of a sequential storage structure is actually the initialization of an array, which is the process of declaring an array of types and sizes and assigning values. The single linked list and sequential storage structure is different, it is not like sequential storage structure so several, it can be very loose, is a dynamic structure. For each linked list, the size and location of the space that it occupies does not need to be allocated in advance, and can be generated according to the system and actual requirements.

So the process of creating a single linked list is a process of dynamically generating a linked list. That is, from the initial state of the "empty table", the nodes of each element are set up, and the linked list is inserted.
An algorithm for creating a whole table of single linked list: Declaring a pointer p and counter variable 1; initializing an empty list; Let the pointer of l node point to null, that is, to establish a single linked list of the leading node;

Cycle:

Generating a new node assignment to p;
A randomly generated data field p->data; a number assigned to P
Inserts p between the header and the previous new node.

The implementation code is as follows:

The values of n elements are randomly generated, and a single chain table L (header interpolation)
void Createlisthead (linklist *l,int N)
{
    linklist P
    ) with a table head node is established. int i;
    Srand (Time (0));//Initialize random number seed
    *l = (linklist) malloc (sizeof (Node));
    (*l)->next = null;//First set up a single chain of leading nodes for
    (i = 0;i < n;i++)
    {
        p = (linklist) malloc (Sizoef (Node));//Generate new node
        p->data = rand ()% 100 + 1;//the number
        P->next = (*l)->next;
        within random generation (*l)->next = p; Insert to table header
    }

In this code, we always make the new node in the first position, we refer to this algorithm as the head interpolation method.

But in fact, we can also put the new node at the end. This is the normal thinking in line. Each of our new nodes are inserted behind the terminal node, this algorithm is called the tail-plug.

The implementation code algorithm is as follows:

The values of n elements are randomly generated, and a single chain linear table L (trailing interpolation)
void Createlisttail (linklist *l,int N)
{
    linklist p,r
    with header nodes is established. int i;
    Srand (Time (0))///Initialize random number seed
    *l = (linklist) malloc (sizeof (Node));//For entire linear table
    r = *l;//r to point to tail node for
    (i = 0;i < n;i++)
    {
        p = (node *) malloc (sizeof (node));//Generate new node
        p->data = rand ()% 100 + 1;//number of randomly generated 100
        r >next = p;//points The pointer to the new node
        r = P;//The current new node is defined as the footer terminal node
    }
    R->next = null;//indicates that the current list ends
}

Note the relationship between L and R, L refers to the entire single linked list, and r to the tail node of the variable, R will continue to change with the loop node, and L is the cycle of growth as a multiple-node linked list.

Here we need to explain, R->next = P means, in fact, just the end of the terminal node R Pointer point to the new node p. Nine, single linked list of the whole table delete

When we do not intend to use this single linked list, we need to destroy it, in fact, it will be released in memory, so as to allow space for other programs or software to use.

The whole table deletion of single chain table is thought as follows:
1. Declare a node p and q;
2. Assign the first node to P;
3. Cycle
Assigning the next node to Q;
Release p;
Assign Q to P.

The implementation code algorithm is as follows:

Initial condition: Sequential linear table L already exists, operation result: Resets L to empty table
Status clearlist (linklist *l)
{
    linklist p,q;
    p = (*l)->next;//p point to first node while
    (p)//not to footer
    {
        q = p->next;
        Free (p);
        p = q;
    }
    (*l)->next = null;//header node Pointer field is null return
    OK;
}
10. The advantages and disadvantages of single chain table structure and sequential storage structure

A simple comparison is made between the single chain table structure and the sequential storage structure.
1, storage allocation mode :
The sequential storage structure has a contiguous storage unit that still stores the data elements of the linear table.
The single linked list uses a chain-type storage structure, which stores the linear table with an arbitrary set of storage units.

2, Time performance :
Find:
-Sequential Storage structure O (1)
-Single link table O (n)

Inserting and deleting
-Sequential storage structure requires an average of half of the elements of the table to be moved, the time is O (n)
-the insertion and deletion time is only O (1) after a single linked list is placed on a pointer

3, Space performance
-Sequential storage structure needs to be allocated storage space, divided into large, waste, small easy to occur overflow.
-Single linked lists do not need to allocate storage space, as long as there can be allocated, the number of elements are unrestricted.

Through the above comparisons, we can draw some empirical conclusions:


If the linear table needs to be frequently searched, rarely enters inserts and deletes the operation, should adopt the sequential storage structure .
If it is necessary to insert and delete frequently, it is advisable to adopt single linked list structure .
For example, in game development, for user registration of personal information, in addition to the registration of inserted data, most of the time is read, so should consider using sequential storage structure. The game of the player's weapons or equipment list, as the player in the course of the game, may be added or deleted at any time, at this time should use a single linked list is more appropriate. Of course, this is just a simple analogy. In real-life software development, the issues to be considered are much more complicated.

When the number of elements in a linear table changes greatly or does not know how large, it is best to use a single linked list structure, so that you can not consider the size of storage space problem .
and If you know the approximate length of a linear table in advance , such as 12 months a year, this sequential storage structure is much more efficient .

In a word, the sequential storage structure of the linear table and the structure of the single linked list have their advantages, which is not to say which is not good, and according to the actual situation, it is necessary to use which kind of data to meet the needs and performance. 11, static linked list

The C language has a pointer capability that makes it easy to manipulate addresses and data in memory, which is more convenient and flexible than other advanced languages.
Later object-oriented language, such as Java, C #, and so on, although not using pointers, but because of the activation of the object-referencing mechanism, from a certain point of view also indirectly implement some of the role of the pointer. But for some languages, such as BASIC, Fortran and other early programming high-level language, because there is no pointer, linked list structure can not be implemented.

Some people think of using arrays instead of pointers to describe linked lists.

First, we use the elements of the array to consist of two data fields, and cur. In other words, each of the following tables in the array corresponds to a data and a cur. The data field is used to hold the data element, which is usually the data we want to process, and cur corresponds to the next pointer in the single list, and the following table in the array that the element follows, we call the cur the cursor.

We call this list of arrays described as static linked lists, and this method of description is called the cursor implementation method .

For our convenience in inserting data, we usually make the array larger so that there are some free space that can be easily inserted to avoid overflow.

The static chain table storage structure of linear table
#define MAXSIZE 1000//assume the maximum length of the linked list 1000
typedef struct
{
    elemtype data;
    int cur;//cursor (Cursor), indicating no pointing
}component,staticlinklist[maxsize] when 0;

In addition, we treat the first and last elements of the array as special elements, without data. We usually refer to an unused array element as an alternate list. And the first element of the array, the cur of the element with subscript 0, holds the following table of the first node of the standby list; The cur of the last element of the array holds the following table of the first numeric element, equivalent to the function of the head node in a single linked list, and 0 ² when the entire list is empty.

One dimension array space in a component chain into a standby list
//space[0].cur as head pointer, "0" indicates null pointer
Status initlist (staticlinklist spaces)
{
    int i;
    for (i = 0;i < maxsize-1;i++)
        space[i].cur = i + 1;
    Space[maxsize-1].cur = 0;//current static list is null return
    OK;
}
1. Insert operation of static linked list

Static linked list to solve is: How to use static simulation of dynamic chain table structure of the allocation of storage space, when needed to apply, do not need to release.

As we said earlier, in a dynamic list, the application and release of nodes are malloc () and free () two functions. In the static list, the operation is an array, does not exist like a dynamic list of applications and release problems, so we need to implement these two functions.

to identify which components in the array are not being used, the solution is to link all unused and deleted components with a cursor to an alternate list, and each time an insert is made, the first node on the standby list can be taken as the new node to be inserted.

If the standby space list is empty, return the allocated node below the table, otherwise return 0
int malloc_sll (staticlinklist spaces)
{
    int i = space[0].cur;// Cur value of the first element of the current array
    if (space[0].cur)
    {
        space[0].cur = space[i].cur;//due to a component to use
                        //So we, You have to use its next component as a standby
    } return
    i;
}

inserting elements

Insert the new data element e
Status Listinsert (staticlinklist l, int i,elemtype e)
{
    int j,k,l
    before the first element in L; K = max_size-1;//Note K First is the last element of the following table
    if (I < 1 | | | i > listlength (L) + 1) return
        ERROR;
    j = Malloc_ssl (l);//Gets the subscript if (j) {L (j) of the Idle component
    . Data
        = e;//The following table to assign a value to this component for
        (L = 1;l <= i-1;l++)// Equivalent to the cyclic list, find the i-1 bit
        {
            k = l[k].cur;
        }
        L[j].cur = l[k].cur;//The new first element element points to the original I element
        l[k].cur = j;//The i-1 element points to the new first element return
        OK;
    return ERROR;
}

In this way, we realized in the array, the implementation does not move elements, but inserted into the operation of the data. 2. Static linked list delete operation

As before, when you delete an element, it's the function free () that needs to release the node. We also have to achieve it ourselves.

Delete in L data element e
Status listdelete (staticlinklist l,int i)
{
    int J, K;
    if (I < 1 | | | i > listlength (L)) return
        ERROR;
    K = max_size-1;
    for (j = 1;j < = i-1;j++)//is equivalent to traversing the list
    {
        k = l[k].cur;
    }
    j = l[k].cur;//The array to be deleted is assigned to J
    Free_sll (L,J);//Call delete function return
    OK;
}
Recycle free nodes with k below table to standby list
void Free_ssl (staticlinklist space,int k)
{
   Space[k] = space[0].cur;// Assigns the subscript of the original first point to the new first bit
   space[0].cur = k;//the component to be removed assigns the first element cur
}

The static linked list is the related implementation of the corresponding other operations. Like Listlength.

Initial condition: Static linked list L already exists. Action Result: Returns the number of data elements in L
int listlength (staticlinklist l)
{
    int j = 0;
    int i = l[maxsize-1].cur;
    while (i)
    {
        i = l[i].cur;
        j + +;
    }
    return j;
}
3. Static link list advantages and disadvantages

Advantage: when inserting and deleting operations, the disadvantage of moving a large number of elements in a sequential storage structure is improved by modifying the cursor without moving the elements.

Disadvantages:
① does not address the problem that the table length is difficult to determine for continuous storage allocation
② lost the sequence. Characteristics of random storage structure 12, cyclic chain list

For a single linked list, because

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.