【2.2链表 】链表中倒数第k个结点

题目描述

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

思路一

使用一个长度为k的尺子,pre先走k-1步,然后nex再开始走,当pre到达最后一个节点时,则nex所指向的就是倒是第k个结点

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

class Solution:
    def FindKthToTail(self, head, k):
        # 使用一个长度为k的尺子,pre先走k-1步,然后nex再开始走,
        # 当pre到达最后一个节点时,则nex所指向的就是倒是第k个结点
        if head == None or k < 1:
            return None
        pre = nex = head
        i = 0
        while i < k-1:
            i += 1
            if pre.next == None:
                return None
            else:
                pre = pre.next

        while pre.next != None:
            pre = pre.next
            nex = nex.next
        return nex

思路二

把链表的node存入list中,然后返回list中倒数第k个元素

class Solution:
    def FindKthToTail(self, head, k):
        # 把链表的node存入list中,然后返回list中倒数第k个元素
        if k < 1:
            return None
        node = []
        while head != None:
            node.append(head)
            head = head.next
        if len(node) >= k:
            return node[-k]
        else:
            return None
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值