Data structure-chain-based storage correlation algorithm for linear tables (i) (C language Implementation)

Source: Internet
Author: User

A brief introduction to the list of why linear lists are needed

Of course, in order to overcome the shortcomings of the order table, in the Order table, do insert and delete operations, the need for a large number of moving elements, resulting in efficiency degradation.

Classification of linear lists
    • Follow the link method:
    • By implementation angle:
The creation of linear linked lists and the idea of simple traversal algorithm

Create a linked list and make a simple traversal of the data on the linked list.

Algorithm implementation
# include <stdio.h># include <stdlib.h>typedef struct node{int data;//data domain struct Node * pnext;//pointer field by    The pointer field can refer to the next node "whole", not a part; The pointer points to the data that is exactly the same as his own data, from the structural level, that is, the individual points to the whole, (here is the popular argument, the implementation is not the case) below the code to explain.  }node,*pnode; node = = struct node; Pnode ==struct Node * pnode create_list (void)//For a list in the chain, we just need to find the "head pointer" address just fine, then we can confirm the list, so we directly let him return the address of the head pointer {int len;//    Number of active nodes int i; int Val; The value Pnode phead = (pnode) malloc (sizeof (node)) used to temporarily store the node entered by the book. The request system allocates a node-sized space if (NULL = = phead)//If the pointer is pointing to NULL, the dynamic memory allocation fails because the first node in a linked list and        Trailing nodes are null after, no other element {printf ("Failed to allocate memory, program terminates");     Exit (-1);        } pnode Ptail = phead;//declares a tail pointer and initializes the pointer to the head node Ptail->data = null;//empties the data field of the tail pointer, after all, and is a node (the logic of emptying the words more in line with the pointer, but not emptying is no problem)    printf ("Please enter the number of nodes to be generated for the list: len =");    scanf ("%d", &len);        For (I=0;i < len;i++) {printf ("Please enter the value of%d nodes", i+1);        scanf ("%d", &val); Pnode pnew = (pnode) malloc (SizeoF (node));//Create a new node so that the pointer points to each node (loop over Len) if (NULL = = pnew)//If the pointer points to NULL, the dynamic memory allocation fails, the Pnew data type is the Pnode type, which is the pointer type, the pointer to the address, such as If the address of the address is empty, in other words, the equivalent of only the head pointer, or only the tail pointer, the tail pointer should not be, because the first linked list is only one//head pointer, so say, if P        New points to NULL, indicating that the memory is not allocated, and that the linked list is still an empty list of only one head node. {printf ("Memory allocation failed, program terminated run!            \ n ");        Exit (-1); } pnew->data = val; Depositing valid data into pnew ptail->pnext = pnew;   Hang the pnew in the back of the Ptail (that is, the Ptail pointer field, string up) Pnew->pnext = null;//to empty the pnew pointer field ptail = pnew; In the pnew assignment to the Ptai, so that it can loop, the realization of connecting in turn (and we want to just put the first node on the head node, followed by sequentially, that is, the second//node hanging on the first node of the pointer field), this place is said before, to give PHE  Ad an "reason for aliases"/* If that's not the case, the code reads: Pnew->data = val;//a temporary node Phead->pnext = pnew;//to Hang pnew on Phead pnew->pnext =null; This temporary node at the very end of the empty comment out of this line of code is problematic, the above commented out of the meaning of the code is the head node after eachNodes are hung on the head node, causing the pointer domain of the node behind the head node to be lost (no pointing), and we're thinking of just hanging the first node on the head node, followed by a second Node hangs on the first node of the pointer field, and so on, it is obvious that the above commented out code is not implementation of this function, Ptail here is equivalent to the role of a broker, similar to the two number exchange algorithm in the role of the middle variable, in a linked list Phead is the head node,                        This is only one in a linked list, but if you assign a property of this node to another variable (ptail), then Ptail is the equivalent of another head pointer, and of course it can be looped.    */} return phead;//returns the address of the head node}void traverse_list (Pnode phead)//How to traverse, is not the same as before with the array, thought the array is continuous, here discontinuous {    Pnode p = phead->pnext;        while (NULL! = p) {printf ("%d", p->data);    p = p->pnext; } printf ("\ n");}                       int main (void) {Pnode Phead = null;//is equivalent to struct node * phead = NULL; Assigns the address of the first node to Phead (after the first and last nodes in a list are NULL, there are no other elements)    Pnode equivalent to struct Node * Phead = Create_list ();    Traverse_list (Phead);  return 0;}
Run the Demo

Algorithm Summary

This is just a simple example, where the algorithm used to insert the node is the tail interpolation method, the following is a specific algorithm.

Realization of algorithm idea by linear chain header interpolation

Starting with an empty table, each time the data is read, a new node is generated, the read-in data is stored in the data field of the new node, and the new node is inserted after the table header node of the current table.

Algorithm implementation
# include <stdio.h># include <stdlib.h>typedef struct node{int data;    struct Node * PNEXT;  }node,*pnode;    traversal void Traverse_list (Pnode phead)//How to traverse, is not as before with the array, thought the array is continuous, here is not contiguous {pnode p = phead->pnext;        while (NULL! = p) {printf ("%d", p->data);    p = p->pnext; } printf ("\ n");}        Pnode create_list (void) {Pnode phead = (pnode) malloc (sizeof (NODE));         Phead->pnext = NULL;        printf ("Please enter the length of the linked list to be generated \ n");        int n;        int Val;        scanf ("%d", &n);            for (int i = n;i > 0;i--) {printf ("Please enter%d data", I); Pnode p = (pnode) malloc (sizeof (NODE));//Create a new node p if (NULL = = p) {printf ("Memory allocation failed, program terminated run !                \ n ");            Exit (-1);            } scanf ("%d", &val);            P->data = val; P->pnext = phead->pnext;//Inserts the P node into the table header, where the pointer to the head node is assigned to the P junction//At this point, it can be understood that the P nodes and head nodes are connected,The head pointer is pointing, and it becomes the pointer to the//P node (at this point the P node corresponds to the first node) Phead->pnext = p; } return phead;}    int main (void) {Pnode phead = NULL;    Phead = Create_list ();    Traverse_list (Phead);  return 0;}
Run the Demo

Algorithm Summary

The logical order of the single-linked list using the head interpolation method is the opposite of the order of the input elements, so it is also called the head interpolation method to construct the table method. Why is the reverse order, because in the beginning to build the table, the so-called head interpolation method, is a new node, and then linked to the head node behind, that is, the most late insertion of the node, the distance from the head nodes is closer! The key to this algorithm is p->data = val;p->pNext = pHead->pNext; pHead->pNext = p; . It might be clearer to use a graph.

Realization of algorithm idea by linear chain-list tail interpolation

Head interpolation method to build a linked list Although the algorithm is simple, but the sequence of nodes in the generated list is the opposite of the input order, if you want the order of the two to be consistent, you can use the tail interpolation method, for this need to add a tail pointer r, so that it points to the table of the single-linked table footer.

Algorithm implementation
# include <stdio.h># include <stdlib.h>typedef struct node{int data; struct Node * pnext;} Node,*pnode;    Pnode create_list (void) {Pnode phead = (pnode) malloc (sizeof (NODE));    Phead->pnext = NULL;    printf ("Please enter the length of the linked list to be generated: \ n");    int n;    int Val;     Pnode r = The phead;//r pointer dynamically points to the current footer of the linked list, so that it can be used for tail insertion, and its initial value points to the head node,//Here is a very important point of knowledge, if the data is pointer type, "=" can be understood as a point.    scanf ("%d", &n);        for (int i = 0;i < n;i++) {printf ("Please enter%d data", i+1);        Pnode p = (pnode) malloc (sizeof (NODE)); if (NULL = = p) {printf ("Memory allocation failed, program terminated run!")            ");         Exit (-1);        } scanf ("%d", &val); P->data = val; Assign a value to the data field of the new node P r->pnext = p;//because the first tail pointer R is pointing to the head node, here again the tail pointer is pointing to S//So, node p is already linked to the head node behind the P-  >pnext = NULL;  Empty the pointer field of the new node, and first empty the pointer field of the last node to be null r = p;     R always points to the footer of the single-linked list, thus implementing one after another insert} return phead; }//traversal void Traverse_list (Pnode phead)//How to traverse, is not likeAs before, the array is contiguous, and there is no contiguous {pnode p = phead->pnext;        while (NULL! = p) {printf ("%d", p->data);    p = p->pnext; } printf ("\ n");}    int main (void) {Pnode phead = NULL;    Phead = Create_list ();    Traverse_list (Phead);  return 0;}
Run the Demo

Algorithm Summary

Through the study of the tail interpolation method, further deepen the understanding of the linked list, "=" can be understood as the assignment number, also can be understood as "point", both flexible use, can better understand the related content in the list.
Also, this tail-difference method is actually the method used in the small example in the beginning of this article. The two can be compared to study.

Find the I node (pointer to return this node after finding) find the algorithm idea by ordinal

In a single-linked list, because each node is stored in the next field of its previous nodes, so even if you know the ordinal of the node being accessed, you can not think of the sequence table in order to access the corresponding elements in a one-dimensional array directly, to achieve random access, but only from the list of the head pointer trigger, follow the chain domain next, Search the node one at a point until you find the first node.
To find the first node in the single-linked list of the leading nodes, you need to start from the head pointer L of the * * Single-linked list, starting from the Phead->next, and then scanning along the chain list with the pointer p pointing to the current sweep surface to the node, the initial value pointing to the head node, and the J to the counter, The cumulative number of nodes currently scanned (the initial value is 0). When i==j, the node that the pointer p points to is the node you are looking for.

Code implementation
# include <stdio.h># include <stdlib.h>typedef struct node{int data; struct Node * pnext;} Node,*pnode;    Pnode create_list (void) {Pnode phead = (pnode) malloc (sizeof (NODE));    Phead->pnext = NULL;    printf ("Please enter the length of the linked list to be generated: \ n");    int n;    int Val;                        Pnode r = phead;    scanf ("%d", &n);        for (int i = 0;i < n;i++) {printf ("Please enter%d data", i+1);        Pnode p = (pnode) malloc (sizeof (NODE)); if (NULL = = p) {printf ("Memory allocation failed, program terminated run!")            ");         Exit (-1);        } scanf ("%d", &val);         P->data = val;                             R->pnext = p;          P->pnext = NULL;      r = P; } return phead;        }//Find node I nodes * GetID (pnode phead,int i)//Find and return the address of the node, only need the head node and the node to find the ordinal {int J;//count, number of scans node * p;    if (i<=0) return 0;    p = phead;    j = 0;        while ((P->pnext!=null) && (j<i)) {p = p->pnext;    j + +; } if (I==J)//Find the first Inode return p;    else return 0;    }//Traversal void Traverse_list (Pnode phead)//How to traverse, is not as before with the array, thought the array is continuous, here is not contiguous {pnode p = phead->pnext;        while (NULL! = p) {printf ("%d", p->data);    p = p->pnext; } printf ("\ n");}    int main (void) {Pnode phead = NULL;    int n;    NODE * FLAG;    Phead = Create_list ();    Traverse_list (Phead);    printf ("Please enter the sequence of nodes you want to find:");    scanf ("%d", &n);    Flag = GetID (phead,n); if (flag! = 0) printf ("Found!    "); else printf ("Not Found!"         ") ;  return 0;}
Run the Demo

Finding algorithm ideas by value

Lookup by value refers to finding whether there is a node with a value equal to Val in a single-linked list, starting from the head node pointed to by the head pointer of the single-linked list, and then comparing the value of the node to the given Val, and returning the result.

Code implementation
# include <stdio.h># include <stdlib.h> #include <cstdlib>//In order to always appear null undefined error message typedef struct node{I    NT data; struct Node * pnext;} Node,*pnode;    Pnode create_list (void) {Pnode phead = (pnode) malloc (sizeof (NODE));    Phead->pnext = NULL;    printf ("Please enter the length of the linked list to be generated: \ n");    int n;    int Val;                        Pnode r = phead;    scanf ("%d", &n);        for (int i = 0;i < n;i++) {printf ("Please enter%d data", i+1);        Pnode p = (pnode) malloc (sizeof (NODE)); if (NULL = = p) {printf ("Memory allocation failed, program terminated run!")            ");         Exit (-1);        } scanf ("%d", &val);         P->data = val;                             R->pnext = p;          P->pnext = NULL;      r = P; } return phead;         }//Find by Value node * GetKey (Pnode phead,int key) {node * p;    p = phead->pnext;              while (P!=null) {if (P->data! = key) {p = p->pnext;//This place is going to be handled, otherwise it will point to the other part of the system emmm if (p->p next = = NULL) {printf ("Sorry, not to find the data for the node you are querying!                    "); Return p;//this way, if you can't find it, you can exit the loop instead of pointing at it all the time.    Causes a pointing to system memory Emmm}} else break; } printf ("Your search for%d found!")                 ", P->data);          return p;    }//Traversal void Traverse_list (Pnode phead)//How to traverse, is not as before with the array, thought the array is continuous, here is not contiguous {pnode p = phead->pnext;        while (NULL! = p) {printf ("%d", p->data);    p = p->pnext; } printf ("\ n");}    int main (void) {Pnode phead = NULL;      int Val;    Phead = Create_list ();    Traverse_list (Phead);    printf ("Please enter the value of the node you are looking for:");    scanf ("%d", &val);             GetKey (Phead,val);  return 0;}
Run the Demo

Algorithm Summary

Two algorithms are similar, the first one by ordinal search, defined a count variable J, it has two functions, the first function is to record the number of nodes, the second role is to limit the pointer to the range, to prevent the pointer pointing to other places. The second is to find by value, and of course you can use the same method to limit the scope, preventing the pointer from pointing to another location. Or, as written above, add a judgment, if the end of the table is empty, exit the loop.

Advantages and disadvantages of linear lists reference
    • Data structure-in C language Description (second edition) [Shang]
    • Data structure (C language version) [Min, 聯繫]

Data structure-chain-based storage correlation algorithm for linear tables (i) (C language Implementation)

Related Article

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.