/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * @author Senky * @date 2023.04.18 * @par url https://www.nowcoder.com/creation/manager/content/584337070?type=column&status=-1 * @brief (1)k为0返回NULL (2)k大于链表长度返回NULL (3)k等于链表长度返回头结点 * @param pHead ListNode类 * @param k int整型 * @return ListNode类 */ struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) { // write code here struct ListNode* first =pHead; struct ListNode* second =pHead; struct ListNode* result = NULL; int count = 0; /*Count the length of the chain table by variable count*/ while(first) { count++; first = first->next; } if(0 == k) result = NULL; else if(k > count) result = NULL; else if(k == count) result = pHead; for(int i = 0; i < count -k; i++) { second = second->next; result = second; } return result; }
Algorithm:
倒数第k个,就是正数第n-k+1个,从0开始就是输出第n-k个