链表中倒数第K个结点

来源:互联网 发布:济南网络推广 编辑:程序博客网 时间:2024/06/06 00:42

求链表中倒数第k个结点思路:

(a)第一个指针在链表上先走k-1步 (b)把第二个指针指向链表的头结点 (c) 两个指针一同沿着链表向前走。
当第一个指针指向链表的尾结点时,第二个指针指向倒数第k个结点

如图:
这里写图片描述

C代码

typedef struct list_node{    int value;    struct list_node *next;}list_node;list_node* find_kth_to_tail(list_node* list_head, unsigned int k){    list_node* head = NULL;    list_node* behind = NULL;    int i = 0;    if (list_head == NULL || 0 == k)        return NULL;    // head pointer walk k-1 step first    head = list_head;    for(i=0; i < k-1; ++i){        if (head->next != NULL)            head = head->next;        else // list node less than k nodes            return NULL;    }    // head pointer and behind pointer walk together    behind = list_head;    while (head->next != NULL){        head = head->next;        behind = behind->next;    }    return behind;}
原创粉丝点击