思路1:数学思维
倒数第k个,即整数第len-k个
struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) {
if(pHead == NULL) return pHead;
int len = 0;
struct ListNode* pcur = pHead;
while(pcur != NULL)
{
len++;
pcur = pcur->next;
}
if(k>len)return NULL;
for(int i = 0;i<len-k;i++)
{
pHead = pHead->next;
}
return pHead;
}
思路2:利用栈
设置一个10e+9大小的指针数组模拟栈来存放每个节点的指针,在根据k来选择输出哪个节点
struct ListNode* FindKthToTail(struct ListNode* pHead, int k) {
if (pHead == NULL) return pHead; // 链表为空,直接返回
struct ListNode** node_position = (struct ListNode**)malloc(sizeof(struct ListNode*)*1e+9); // 创建一个指向指针数组的指针
struct ListNode* pcur = pHead;
int top = -1;
while (pcur != NULL) // 节点指针依次入栈
{
node_position[++top] = pcur;
pcur = pcur->next;
}
// 由题意可知,特殊情况返回空指针,释放内存
if (k > top + 1 || k == 0)
{
free(node_position);
return NULL;
}
// 定位要输出的节点
for (int i = 1; i < k; i++)
{
top--;
}
struct ListNode* result = node_position[top]; // 创建指针变量接收该节点,便于释放数组
free(node_position);
return result;
}
上述代码,即为本人所思考出的本题答案,该解法均为暴力解,若有好的思路后续再补充