算法题-求链表中倒数第k个节点

40 篇文章 0 订阅
38 篇文章 0 订阅

时间限制:1秒 空间限制:32768K
本题知识点: 链表
题目描述

输入一个链表,输出该链表中倒数第k个结点。

思路1:
遍历两次数组,第一次先统计出来个数n,第二次再求出n-k+1,将求倒数第k节点的问题转化为正数第n-k+1的问题

C++

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int m) {
    if(pListHead==NULL||m<1)return NULL;
        int count = 0;
        ListNode* pFind = pListHead;
        while(pFind != NULL){//记录链表总节点数,方便后续倒数转正数
            count+=1;
            pFind = pFind->next;
        }
        int pos = count - m + 1;//将倒数位置转化成正数位置
        if( pos < 1)return NULL;
        int flg = 1;
        pFind = pListHead;
        while(pFind != NULL && flg != pos){
            pFind = pFind->next;
            flg++;
        }
        return pFind;
    }
};

Python

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindKthToTail(self, head, k):
        if k<=0 or head==None:
            return None
        count=0
        pFind=head
        while pFind != None:
            count=count+1
            pFind=pFind.next
        if count<k:
            return None
        pos=count-k+1
        flg=0
        pFind=head
        while pFind!=None:
            flg=flg+1
            if flg==pos:
                return pFind
            pFind=pFind.next
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值