The basic operation of C language to realize single linked list (not lead node)

Source: Internet
Author: User
Tags data structures int size

The importance of linked lists in data structures and algorithms is self-evident. Here we will use C to implement the basic operation of the linked list (single linked list). For the basic concept of the list, please refer to the "Data structure and algorithm of the list" this blog. Sample code uploaded to Https://github.com/chenyufeng1991/LinkedList. In this case, the single linked list has no head nodes, and the head pointer points directly to the first node. Example of a lead node I'll explain it later.

(1) Defining the node type of a single linked list

typedef int ELEMTYPE;

Defines a single link table node type
typedef struct listnode{
    elemtype element;      Data domain
    struct listnode *next;   Address domain
}node;

(2) Initialization of linear table

1. Initialize the linear table, that is, the table head pointer of the single linked table is empty
void Initlist (Node *pnode) {

    pnode = null;
    printf ("%s function execution, initialization succeeded \ \ \ __function__");
}
When a header node is declared, the first node is set to NULL, that is, the data field and Address field are set to NULL to complete the initialization of the linked list.

(3) Create a linear table

2. Create a linear table, this function enter negative numbers terminate read data node *creatlist (node *phead) {node *p1;//header node, always point to header node *p2;//footer node, always point to the last element of the list P1 = P2 = (node *) malloc (sizeof (node));
        Request new node, allocate space if (P1 = null | | p2 = = NULL) {printf ("Memory allocation failed \ n");
    Exit (0);

    } memset (P1,0,sizeof (Node));    scanf ("%d", &p1->element);         Enter the value of the new node P1->next = NULL;
            The new node's pointer is set to NULL while (P1->element > 0) {//Enter a value greater than 0 to continue until the value entered is negative if (Phead = null) {//empty table, Access header          Phead = p1;       Direct P1 as a head node can also be understood to point the Phead head node to p1}else{p2->next = p1;                Non-empty table, Access table tail} p2 = p1;    After inserting the P1, the P1 is the tail node, so P2 to point to the tail node P1 = (node *) malloc (sizeof (node));
            Re-request a node if (P1 = null | | p2 = = NULL) {printf ("Memory allocation failed \ n");
        Exit (0);
        } memset (P1,0,sizeof (Node));
        scanf ("%d", &p1->element);
    P1->next = NULL; printf ("%s function execution, linked list creation succeeded \ n", __function__);           return phead; Returns the head pointer of a linked list}

I'm here to enter the element manually, until I enter 0 or the negative number stops.


(4) Print linked list

3. Print linked list, the list of the traversal of the
void Printlist (Node *phead) {
    if (NULL = = phead) {   //linked list is empty
        printf ("%s function execution, linked list is null \", __ function__);
    } else{
        while (NULL!= phead) {
            
            printf ("%d", phead->element);
            Phead = phead->next;
        }
        printf ("\ n");
    }

Print using Address field order.


(5) Clear the list

4. Clears all the elements in the linear table L, releasing all the nodes in the single linked list L to make it an empty table
void clearlist (node *phead) {

    node *pnext;            Defines a node that is adjacent to Phead, understood as the next node of the current node
    if (Phead = = NULL) {
        printf ("%s function execution, linked list is empty \ \", __function__);
    }
    while (Phead->next!= NULL) {

        Pnext = phead->next;//Saves the next node's pointer free
        (phead);   Releases the current node
        phead = Pnext;      Point to Next node
    }
    printf ("%s function execution, linked list cleared \ \ __function__");
}

To verify whether the empty is successful, you can use the list in (4) to print the test.

(6) Calculate the length of the linked list

5. Returns the length of the single linked list
int sizelist (Node *phead) {

    int size = 0;
    while (Phead!= NULL) {

        size++;
        Phead = phead->next;
    }
    printf ("%s function execution, linked list length%d \ n", __function__,size);
    return size;    The actual length of the linked list
}

That is, how many nodes are counted.

(7) to determine whether the linked list is empty

6. Check whether the single linked list is empty, if empty then return 1, otherwise return 0
int isemptylist (Node *phead) {
    if (Phead = null) {

        printf ("%s function execution, linked list is null \", __ FUNCTION__);
        return 1;
    }
    printf ("%s function execution, linked list not null \ \ __function__");

    return 0;
}

(8) Find a location element in the list

7. Returns the elements of POS nodes in a single list, and if the POS is out of range, stop the program running
void GetElement (Node *phead, int pos) {

    int i = 0;
    if (POS < 1) {
        printf ("%s function execution, POS value illegal \ n", __function__);
    }

    if (Phead = = null) {
        printf ("%s function execution, linked list is empty \ \ __function__")
    ;

    while (Phead!= NULL) {

        i++;
        if (i = = pos) {break
            ;
        }
        Phead = phead->next;    Move to next node
    }
    if (I < POS) {                  //pos value exceeds list length
        printf ("%s function executes, POS value exceeds list length \ n", __function__);
    }

    printf ("%s function execution, position%d element is%d\n", __function__,pos,phead->element);
}

(9) Return the memory address of an element value in the list

8. Find the first element with a given value x from a single list, or return the storage address of the data field of the node if the lookup succeeds, or return null
elemtype* getelemaddr (node *phead, Elemtype x) {
    if ( NULL = = phead) {

        printf ("%s function execution, list is empty \ \ __function__");
        return NULL;
    }

    while ((phead->element!= x) && (NULL!= phead->next)) {//Determine whether to the end of the list and whether there is an element to be found
        Phead = phead-> Next;
    }

    if ((phead->element!= x) && (phead!= NULL) {
        //when the last node is reached
        printf ("%s function execution, no x value found in the list \ n", __function __);
        return NULL;
    }

    if (phead->element = = x) {
        printf ("%s function executes, the address of element%d is 0x%x\n",__function__,x,& (phead->element));
    }

    Return & (Phead->element);//Returns the address of the element
}

(10) Modify the value of a node

9. Change the value of the POS node in the single linked list to X, and if the modification returns 1 successfully, return 0
int Modifyelem (Node *pnode,int pos,elemtype x) {

    int i = 0;
    if (NULL = = pnode) {
        printf ("%s function execution, list is empty \ \ __function__");
        return 0;
    }

    if (POS < 1) {

        printf ("%s function execution, POS value illegal \ n", __function__);
        return 0;
    }

    while (Pnode!= NULL) {

        i++;
        if (i = = pos) {break
            ;
        }
        Pnode = pnode->next; Move to next node
    }

    if (I < POS) {                 //pos value is greater than the chain table length

        printf ("%s function execution, POS value out of list length \ n", __function__);
        return 0;
    }
    pnode->element = x;
    printf ("%s function execution \ n", __function__);

    return 1;
}

(11) Table header inserts a node

10. Insert an element
int insertheadlist (node **pnode,elemtype insertelem) {

    node *pinsert to the table header of a single linked table;
    Pinsert = (node *) malloc (sizeof (node));
    memset (pinsert,0,sizeof (Node));
    Pinsert->element = Insertelem;
    Pinsert->next = *pnode;
    *pnode = Pinsert;          The head node *pnode points to the node just inserted, noting the order of the previous line of code;
    printf ("%s function executes, insert element to table header \ n", __function__);

    return 1;
}

(12) Insert a node at the end of the table

11. Add an element
int insertlastlist (node **pnode,elemtype insertelem) {

    node *pinsert to the end of a single linked list;
    Node *phead;

    Phead = *pnode;
    Pinsert = (node *) malloc (sizeof (node)); Apply for a new node
    memset (pinsert,0,sizeof (node));
    Pinsert->element = Insertelem;

    while (Phead->next!= NULL) {
        phead = phead->next;
    }
    Phead->next = Pinsert;   Point the next node at the end of the list to the newly added node

    printf ("%s function executes, insert element to footer \ n", __function__);
    
    return 1;
}

(13) Test function

int main (int argc, const char * argv[]) {

    Node *plist;            Statement head node

    initlist (plist);
    printlist (plist) of the linked list initialization;       Traverse list, Print List

    plist = Creatlist (plist);//Create a list
    printlist (plist);

    Sizelist (plist);        The length of the linked list is
    printlist (plist);

    Isemptylist (plist);     Determine if the linked list is an empty list

    getelement (plist,3);  Gets the third element, and returns 0
    printlist (plist) If the element is less than 3;

    GETELEMADDR (plist,5);   Get the memory address of element 5

    Modifyelem (plist,4,1);  Modifying the element on position 4 in the list to 1
    printlist (plist);

    Insertheadlist (&plist,5);   The header inserts the element 5
    printlist (plist);

    Insertlastlist (&plist,10);  The footer inserts the element
    printlist (plist);

    Clearlist (plist);       Clear the list
    printlist (plist);

    return 0;
}

This article refers to: http://www.cnblogs.com/renyuan/archive/2013/05/21/3091506.html


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.