链表中倒数第K个结点
2017-09-23 10:43
225 查看
求链表中倒数第k个结点思路:
(a)第一个指针在链表上先走k-1步 (b)把第二个指针指向链表的头结点 (c) 两个指针一同沿着链表向前走。
当第一个指针指向链表的尾结点时,第二个指针指向倒数第k个结点
如图:
C代码
(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; }
相关文章推荐
- 面试题:输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针。
- 链表中倒数第k个结点
- 剑指Offer:面试题15 链表中倒数第k个结点
- 13、输入一个单向链表,输出该链表中倒数第k个结点
- 链表中倒数第k个结点
- 剑指offer:输出该链表中倒数第k个结点
- 链表中倒数第k个结点
- 华为oj 输出单向链表中倒数第k个结点
- 面试题15:链表中倒数第K个结点
- 剑指offer代码解析——面试题15求链表中倒数第K个结点
- 华为OJ:输出单向链表中倒数第k个结点
- 码农小汪-剑指Offer之12 -链表中倒数第k个结点
- 剑指offer——面试题15:链表中倒数第k个结点
- 【剑指Offer面试编程题】题目1517:链表中倒数第k个结点--九度OJ
- 链表中倒数第k个结点
- 链表中倒数第k个结点
- 剑指Offer-链表中倒数第k个结点
- 输入一个单向链表,输出该链表中倒数第K个结点
- 链表中倒数第k个结点
- 输入链表输出该链表倒数第k个结点java实现