Linked list (5)----Find the penultimate node of the linked list

Source: Internet
Author: User

1, linked list definition

typedef struct LISTELEMENT_T_ {    void *data;    struct Listelement_t_ *next;} listelement_t;typedef struct list_t_{    int size;    int capacity;    listelement_t *head;    listelement_t *tail;} list_t;



2. Find the K node data of the linked list

Set the speed pointer, the fast pointer ahead of the slow pointer K-1 nodes, and then the speed pointer and then traverse the linked list, when the fast pointer over the end of the list, the slow pointer is the bottom of the K node.

void  *searchrkthnode (list_t *list, unsigned int k) {    if (List = = NULL | | list->head = NULL | | k = = 0)//k is an unsigned number , so it is necessary to determine whether it is 0        return NULL;    listelement_t *pfast = list->head;    while (K > 1 && pfast! = NULL) {        --k;        Pfast = pfast->next;    }    K>1 indicates that the number of nodes is less than K, pfast=null indicates that the list is k-1 node    if (k > 1 | | pfast = = NULL)        return null;    listelement_t *pslow = list->head;    while (pfast->next! = NULL) {        pfast = pfast->next;        Pslow = pslow->next;    }    return pslow->data;}






Linked list (5)----Find the penultimate node of the 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.