剑指offer:链表中倒数第k个结点 python实现

链表中倒数第k个结点

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

解题思路

暴力求解:

  1. 判断链表是否为空;
  2. 复制链表,遍历一遍统计其长度;
  3. 如果长度小于k。则返回None;
  4. 否则,返回其长度-k的链表。
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        if not head:
            return None
        head_copy=head
        cnt=1
        while head.next:
            head=head.next
            cnt+=1
        if cnt<k:
            return None
        for i in range(cnt-k):
            head_copy=head_copy.next
            
        return head_copy

进阶版,快慢指针,第一个指针先走k步,第二指针再走。当第一个指针走完整个列表时,第二个指针刚好位于倒数第k的节点。
双指针例子:寻找中间节点, 两个指针一起, 第一个指针每次走两步, 第二个指针每次走一步, 快指针指到尾部, 慢指针正好指到中间。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        if not head:
            return None
        if k==0:
            return None
        head_copy=head
        cnt=1
        while head.next:
            head=head.next
            
            if cnt>=k:
                head_copy=head_copy.next
            cnt+=1
        
        if cnt<k:
            return None
            
        return head_copy
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值