1.题目:
2.思路:
快慢指针法 fast, slow, 首先让fast先走k步,然后fast,slow同时走,fast走到末尾时,slow走到倒数第k个节点。
3.我的代码:
C语言:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pListHead ListNode类
* @param k int整型
* @return ListNode类
*/
struct ListNode* FindKthToTail(struct ListNode* pListHead, int k )
{
// write code here
struct ListNode* fast = pListHead; //使用快慢指针法
struct ListNode* slow = pListHead;
while (k--)
{
if (fast == NULL) //考虑特殊情况k>length
{
return NULL;
}
fast = fast->next;
}
while (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
Java:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
ListNode fast = head;
ListNode slow = head;
while (k - 1 != 0) {
if (fast == null || fast.next == null) {
return null;
}
fast = fast.next;
k--;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
4.答案代码:
C语言:
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
struct ListNode* slow = pListHead;
struct ListNode* fast = slow;
while(k--)
{
if(fast)
fast = fast->next;
else
return NULL;
}
while(fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
Java:
/*
解题思路:
1. 让一个引用从链表起始位置开始,先往后移动k步。注意:k大于链表中节点的情况
2. 让一个引用从链表起始位置开始,两个引用同时往后移动,当前面的引用走到链表末尾时,后面引用停的位置刚好是链表的倒数第k个节点
*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
// 1. front先往后走k步
ListNode front = head;
while(0 != k--){
// 如果front为空,说明k大于链表中节点个数
if(null == front){
return null;
}
front = front.next;
}
// 然后front和back同时往后移动,
// 当front走到末尾的时候,back刚好是倒数第k个节点
ListNode back = head;
while(null != front){
front = front.next;
back = back.next;
}
return back;
}
}