😈博客主页:🐼大家好我叫张同学🐼
💖 欢迎点赞 👍 收藏 💗留言 📝 欢迎讨论! 👀
🎵本文由 【大家好我叫张同学】 原创,首发于 CSDN 🌟🌟🌟
✨精品专栏(不定时更新) 【数据结构+算法】 【做题笔记】【C语言编程学习】
☀️ 精品文章推荐
【C语言进阶学习笔记】三、字符串函数详解(1)(爆肝吐血整理,建议收藏!!!)
【C语言基础学习笔记】+【C语言进阶学习笔记】总结篇(坚持才有收获!)
| 前言 |
| 题目内容 |

原题链接(点击跳转)
| 遍历链表法 |
| 算法图解 |

| 函数实现 |
struct ListNode* getKthFromEnd(struct ListNode* head, int k){
int length = 0;//求链表长度
struct ListNode* cur = head;
while(cur){
length++;
cur = cur->next;
}
cur = head;//cur重新返回头节点
int step = length-k;//第length+1-k个位置只需要向后走length-k步
while(step--){
cur = cur->next;
}
return cur;
}

if(k > length)
return NULL;

struct ListNode* FindKthToTail(struct ListNode* pListHead, int k ) {
// write code here
int length = 0;//求链表长度
int step = 0;
struct ListNode* cur = pListHead;
while(cur){
length++;
cur = cur->next;
}
if(k > length)
return NULL;
cur = pListHead;//cur重新返回头节点
step = length-k;//第length+1-k个位置只需要向后走length-k步
while(step--){
cur = cur->next;
}
return cur;
}

| 快慢指针法 |
| 算法图解 |

| 函数实现 |
struct ListNode* getKthFromEnd(struct ListNode* head, int k){
struct ListNode *fast = head,*slow = head;
while(k--){//fast先走k步
fast = fast->next;
}
while(fast){//fast、slow一起往后走
fast = fast->next;
slow = slow->next;
}
return slow;
}

struct ListNode* FindKthToTail(struct ListNode* pListHead, int k ) {
struct ListNode *fast = pListHead,*slow = pListHead;
if(k == 0)//这里加了k=0的条件判断
return NULL;
while(k--){//fast先走k步
if(fast == NULL)//这里加了fast提前走到NULL的判断
return NULL;
fast = fast->next;
}
while(fast){//fast、slow一起往后走
fast = fast->next;
slow = slow->next;
}
return slow;
}











