BM8 链表中倒数最后k个结点

思路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;
}

上述代码,即为本人所思考出的本题答案,该解法均为暴力解,若有好的思路后续再补充

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值