您的位置:首页 > 其它

链表中倒数第K个结点

2017-09-23 10:43 225 查看
求链表中倒数第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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息