题解 | #链表中倒数最后k个结点#
链表中倒数最后k个结点
https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
假设链表一共有n个节点,倒数第k个就是正数的n-k的下一个节点。所以先找到聊表有多少个节点,再找到第n-k个,返回他的下一个即可
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) {
// write code here
struct ListNode *p;
int len = 0;
p = pHead;
while(p){
len++;
p = p -> next;
}
p = pHead;
if(k > len)return NULL;
else{
for(int i = 0;i < len - k;i++){
p = p -> next;
}
return p ;
}
}