输入一个链表,输出该链表中倒数第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
        pre = None
        while head:
            first = head.next  ##定义新位置
            head.next = pre    ##将当前位置指向前一个位置
            pre = head
            head = first
        count = 1
        while pre:
            if count == k:
                return pre.val
            pre = pre.next
            count +=1     

利用快慢指针:
在这里插入图片描述

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        slow,fast=head,head
        for i in range(k):
            if not fast:
                return None
            fast=fast.next
        while fast:
            slow=slow.next
            fast=fast.next
        return slow
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值