力扣,https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/description/
class Solution {
public ListNode trainingPlan(ListNode head, int cnt) {
if (head == null) {
return null;
}
ListNode i = head, j = head;
int step = cnt;
while (step > 0) {
if (j == null) { // 增加cnt > 链表长度情况的处理
return null;
}
j = j.next;
--step;
}
while (j != null) {
i = i.next;
j = j.next;
}
return i;
}
}
Solution1:
典型的双指针题目。但要考虑到很多边界条件!
注意此题中陷阱很多,具体看书中解释
20181008修改代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
struct ListNode* p1 = pListHead,*p2=pListHead;
int abs_k = k;
if (!k) return NULL;
while (--abs_k > 0) {
if (!p2 || !p2->next)
return NULL;
p2 = p2->next;
}
while (p2->next != NULL) {
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
};
原答案
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
struct ListNode* p1 = pListHead,*p2=pListHead;
int abs_k=k;
if(k==0) return NULL;
while(--abs_k>0){
if(p2 == NULL || p2->next == NULL)
return NULL;
p2=p2->next;
}
while(p2->next!=NULL){
p1=p1->next;
p2=p2->next;
}
return p1;
}
};