West wind data Structure Tutorial (1)--linked list

Source: Internet
Author: User
Tags set set

Today, the students bear asked me some basic data structure problems, I think these basic things should be well understood. In fact, data structure should be the cornerstone of computer technology, all kinds of algorithms are in the data management based on the operation.

So, I'm going to use my spare time to sort out what I've learned, and add some of my own innovative content to a concise data structure tutorial, and then try to delve into some of the innovative approaches and elegant implementations of these things.

Back in the year, high school computer competition career, over and over to chew those who do not understand the knowledge point, it is because of this, I am not good, but also has a solid basic skills, in this, I also want to thank my mentor, we tangshan a Guo Lianfeng teacher.

Well, then I will comb the entire data structure and related important algorithms of the context, I hope that the easy-to-digest, gradually bring you to understand a variety of interesting problems and sophisticated solutions, to appreciate the beauty of data.

The code after the basic test verification, but still do not test the use of the production environment, I caishuxueqian, if there are omissions, but also hope that the vast numbers of netizens criticized.

Introduction to Data structures

Data structure is based on the storage structure of the computer, the most basic is the array, linked list of the two structures.

By the idea of linked list, it is tree structure, tree structure can be very convenient to achieve a variety of fast query, Dynamic Data management and other difficult problems.
Balanced binary tree, should be the most commonly used tree structure, used to do treemap, used to implement set set, can achieve automatic sorting and weighing.

Tree-like structure is a graph, adjacency table is the product of linked list thought, but the graph can also be stored in the form of a matrix.
The graph has the classical problems of the components of Unicom, the search of graphs, the shortest path, the network flow.

Introduction to the list of links

Today we introduce the linked list, because the array is obvious, continuous storage, the computer is more easily implemented.

One of the great benefits of a linked list is that it is not necessary to determine the length of the space, when it is not enough, to apply for a new node and insert it conveniently.

The reason for determining the nature of the data structure is that computer memory is an abstract contiguous space, and if the computer's memory itself is not organized like this, perhaps there is no such thing as a list or linear table of common structure.

Back to the point, the list is actually a dynamic management of computer space, the idea of pointer jump is also the essence of the management data in the computer, we will look at the computer pointer in the end what it looks like.

A pointer is a record of a memory address, typically represented by a 16-digit, 32-bit or 64-bit machine, which refers to the number of bits of the bus to which it is addressed, and we record where the data resides in the computer, and can then find the data at any time.

The implementation of the linked list

To make the list more convenient to traverse and insert, we add one more head node to the list, because we want a convenient description to insert a data anywhere, and if the first node in the list stores the first data, the insert operation is inserted after the node, Then we're not going to be good at defining an operation to insert data to the first node head.

So let's write a list.h file and write the implementation of the linked list in C code:

#ifndef LIST_H#define LIST_H#endif // LIST_H

In the C language, this is defined in order to prevent duplicate references to header files, and because the default is C, we do not add extern "C" identities.

#ifndef LIST_H#define LIST_Htypedefint ListElementType;typedefstruct _list{    ListElementType data;    structlist;#endif // LIST_H

Here is the classic definition of the chain list, must have learned the C data structure of the comrades are also very familiar with, here to explain why to use a ListElementType separate definition of the type, C code does not support the template, the definition of code should be as flexible as possible, the type definition in C to improve code reuse and portability is of great significance. Redefining types often allows the same code to run in different environments.

The classic size_t variable is to let C code on the 32-bit platform and 64-bit platform, the return is 32-bit integer and 64-bit integer, he is often used to describe the memory length, and the scale of course to adapt to the platform.

typedefstructlist;

This definition is also C unique, because the struct type in C must be used in this way struct typename idname , so as to define it, it is convenient to use.

Here we add some action functions:

/* 链表末尾的添加,返回新添加的节点 */list* ListAdd(list* l, ListElementType data);/* 链表任意位置的添加,会添加到l节点的后面,返回新添加的节点 */list* ListInsert(list* l, ListElementType data);/* 删除链表,l是指要删除的节点的上一个节点 */void ListDelete(listlist* ele);/* 判定是否是空 */bool ListIsEmpty(list* l);/* 创建链表节点 */list* ListCreate();

The creation of a linked list node is simple, in the form of C + +, write a constructor that dynamically allocates memory for the node and set the node's next pointer to null:

list* ListCreate() {    list* pList = (listmalloc(sizeof(list));    pList->next = NULL;    return pList;}

It is convenient to judge whether a list is empty, the empty list has only one head node, and the head node does not save the data, so we just need to let ListIsEmpty the function accept the head node of a list as input:

bool ListIsEmpty(list* l) {    return l->next == NULL;}

Here we do not judge L is very null, we can check, but even if found, but also not good processing, so for the sake of simplicity, we simply ask the user must provide us with a non-empty head node, which is modeled after the concept of object in C + +, we call the object's member function, The member function also generally does not determine whether the this pointer is empty.

The insertion function of a linked list is often the most important, and inserting in any position is the core function of a linked list, but it is also simple, as long as you break the list and then insert it:

list* ListInsert(list* l, ListElementType data) {    list* oldnext = l->next;    l->next = ListCreate();    l->next->data = data;    l->next->next = oldnext;    return l->next;}

The deletion of any location is also very important, the memory management of the linked list must be aware, always avoid memory leaks:

void ListDelete(listlist* ele) {    list* pList = l;    while(pList->next != NULL) {        if (pList->next == ele) {            pList->next = ele->next;            Free(ele);            break;        }        pList = pList->next;    }}

To facilitate the user's data addition, write an add function to add the node to the end of the list:

list* ListAdd(list* l, ListElementType data) {    list* pList = l;    while(pList->next != NULL) {        pList = pList->next;    }    return ListInsert(pList, data);}

But this function every call will traverse the entire list, not high efficiency, need attention.

One of the most important features of C language is to simplify programming with macros, and we write a macro to traverse the list to facilitate the traversal of the chain:

/* 链表的遍历宏 */#ifndef list_for_each#define list_for_each(type, ele, list) \    { type ele;         forlist->next; ele != NULL; ele = ele->next) {#endif#ifndef end#define end } } #endif

C language macro function is very powerful, can be any text snippet compiled into the corresponding location, we write a macro so that the user can call:

list_for_each(list*, ele, l)    printf("%d\n", ele->data);end

Is there a high-level language for the foreach effect?

At this point, the basic form of the list has been finished, in the appendix has the complete code, the need for friends to refer to.

Advanced usage of linked lists

Let me discuss the variants of the linked list, which are often of practical value

Double linked list

The emergence of the double-linked list is to solve the list of nodes do not know their own front a node of embarrassment, so in the definition of the node, there is a precursor, a successor, so often can find the last node, to deal with the related things.

Double Cycle linked List

The dual-loop list has a wide range of applications in the Linux kernel and is often used as a simple container for easy traversal, where any position can begin to traverse forward or backward, and can traverse the complete element.

Block Linked list

The array is also a very important structure, but it is not easy to modify, but sometimes, we need the array of continuous random storage characteristics, but also often modified, if the general only from the two ends of the modification, you can take a block list of the solution:

, the Block list is a chain of linked list of arrays, before the addition of data without modifying a large amount of content, only need to add and remove nodes, but also a faster index to the desired data, c++stl in the deque is the classic structure.

Appendix--Full code
/ * list.h * / / * * @Author: sxf* @Date: 2015-04-14 19:44:32* @Last Modified by:sxf* @Last Modified time:2015-04-14 21:04:24*/< /c1>#ifndef List_h#define LIST_H#include <malloc.h>typedef Char BOOL;typedef intListelementtype;typedef struct_list{Listelementtype data;struct_list* Next;}List;/ * Add at the end of the linked list, returning the newly added node * /List* Listadd (List* L, listelementtype data);/ * Any additions to the linked list will be added to the back of the L node, returning the newly added node * /List* Listinsert (List* L, listelementtype data);/ * Delete the linked list, l refers to the previous node of the node to be deleted * /voidListdelete (ListLList* ele);/ * Determine if it is empty * /BOOLListisempty (List* L);/ * Create a linked list node * /List* Listcreate ();/ * Traverse macro for linked list * /#ifndef List_for_each#define List_for_each (type, ele, list) \{type ele; for(Ele =List->next; Ele! = NULL; Ele = Ele->next) {#endif#ifndef End#define END}} #endif/ * Release macro for pointer * /#ifndef Free#define FREE (p) if (p!=null) free (p)#endifList* Listadd (List* L, Listelementtype data) {List* pList = l; while(Plist->next! = NULL)    {pList = plist->next; }returnListinsert (pList, data);}List* Listinsert (List* L, Listelementtype data) {List* Oldnext = l->next;    L->next = Listcreate ();    L->next->data = data; L->next->next = Oldnext;returnL->next;}voidListdelete (ListLList* ele) {List* pList = l; while(Plist->next! = NULL) {if(Plist->next = = ele)            {Plist->next = ele->next; Free (ele); Break;    } pList = plist->next; }}BOOLListisempty (List* L) {returnL->next = = NULL;}List* Listcreate () {List* PList = (List*)malloc(sizeof(List)); Plist->next = NULL;returnPList;}#endif //List_h 
/ * MAIN.C * / / * * @Author: sxf* @Date: 2015-04-14 19:44:24* @Last Modified by:sxf* @Last Modified time:2015-04-14 21:20:00*/< /c7>#include <stdio.h>#include "list.h"List* L = NULL;List* last = NULL;intMain () {L = listcreate ();/ * Low-efficiency add * /    printf("test1:\n"); Listadd (L,3); Listadd (L,5); Last = Listadd (L,8); List_for_each (List*, Ele, L)printf("%d\n", Ele->data); End/ * Recommended additions * /    printf("test2:\n"); Last = Listinsert (last,2); Last = Listinsert (last,3); Last = Listinsert (last,5); List_for_each (List*, Ele, L)printf("%d\n", Ele->data); End/ * How to delete * /    printf("test_del:\n"); List_for_each (List*, Ele, L)if(Ele->data = =2) {Listdelete (L, ele); Break;/ * Delete must interrupt loop in general loop * /} End List_for_each (List*, Ele, L)printf("%d\n", Ele->data); Endreturn 0;}

West wind data Structure Tutorial (1)--linked list

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.