首页 > 试题广场 >

链表中倒数最后k个结点

[编程题]链表中倒数最后k个结点
  • 热度指数:409022 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
输入一个长度为 n 的链表,设链表中的元素的值为 ai ,返回该链表中倒数第k个节点。
如果该链表长度小于k,请返回一个长度为 0 的链表。


数据范围:
要求:空间复杂度 ,时间复杂度
进阶:空间复杂度 ,时间复杂度

例如输入{1,2,3,4,5},2时,对应的链表结构如下图所示:
其中蓝色部分为该链表的最后2个结点,所以返回倒数第2个结点(也即结点值为4的结点)即可,系统会打印后面所有的节点来比较。
示例1

输入

{1,2,3,4,5},2

输出

{4,5}

说明

返回倒数第2个节点4,系统会打印后面所有的节点来比较。 
示例2

输入

{2},8

输出

{}

说明:本题目包含复杂数据结构ListNode,点此查看相关信息
写完了后发现运行200ms,占用内存2w7KB,比起排行翻了好几倍,然后点开排行的代码发现是同样的思路,百思不得其解。然后复制了人家的代码跑了一下,本来人家30ms,3000kb的代码,我拷过来跑一次也是200多ms,2w7KB内存占用,这是为啥嘞???是后续更新的时候用例集增加了吗?
发表于 2025-02-02 01:14:12 回复(0)
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pHead ListNode类 
# @param k int整型 
# @return ListNode类
#
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here
        # 第一遍遍历记录下当前链表的长度
        # 节从1开始,节点位置:链表长度 - 倒数值 + 1
        lenList = 0
        cur = pHead
        while cur is not None:
            lenList = lenList + 1
            cur = cur.next
        if lenList < k :
            return ListNode(None).next
        
        objNodeIdx = lenList - k + 1
        cur = pHead
        for i in range(1,objNodeIdx):# 位置从1开始计数
            cur = cur.next
        return cur

发表于 2024-12-22 13:50:40 回复(0)
from typing import Optional

class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> Optional[ListNode]:
        a = b = pHead
        while a:
            a = a.next
            if not (k := k - 1):
                while a:
                    a, b = a.next, b.next
                return b
发表于 2024-10-12 22:15:20 回复(0)
from math import e
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pHead ListNode类 
# @param k int整型 
# @return ListNode类
#
class Solution:
    def FindKthToTail(self , pHead, k: int):
        # write code here
        if not pHead&nbs***bsp;k < 1:
            return None
        lastNode = pHead

        for _ in range(k-1):
            if lastNode.next:
                lastNode = lastNode.next
            else:
                return None
        while lastNode.next:
            lastNode = lastNode.next
            pHead = pHead.next
        return pHead

发表于 2024-09-15 20:07:55 回复(0)
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here
        p, count, len1 = pHead, 0, self.Lenth(pHead)
        q = ListNode(0)
        if len1 < k:
            return q.next   # 返回空链表
        while True:
            if count == len1 - k:   # 遍历到倒数第k节点,输出
                return p
            p = p.next
            count = count + 1

        
    def Lenth(self, pHead): # 计算链表长度
        count  = 0
        while pHead:
            pHead = pHead.next
            count = count + 1
        return count

发表于 2024-09-15 12:47:27 回复(0)
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here
        tail = pHead
        kth = pHead
        for _ in range(k):
            if kth:
                kth = kth.next
            else:
                return None
        while kth:
            tail = tail.next
            kth = kth.next
        return tail

编辑于 2024-02-05 20:43:16 回复(1)
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here
        slow = pHead
        fast = pHead
        index = 0
        while fast != None:
            fast = fast.next
            index += 1
            if index > k:
                slow = slow.next
        if index < k:
            return None
        else:
            return slow

发表于 2023-08-17 09:04:36 回复(0)
#最简单的理解就是将链表转成数组,然后把后k个数据提出来,再组成链表
lass Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here
        num = []
        while pHead:
            num.append(pHead.val)
            pHead = pHead.next

        n = len(num)
        if n < k:
            return None
        numk = []
        for i in range(n-k,n):
            numk.append(num[i])
        new = ListNode(0)
        cur = new
        for m in numk:
            cur.next = ListNode(m)
            cur = cur.next
        return new.next

发表于 2023-05-30 16:36:00 回复(0)
空间复杂度O(1),时间复杂度O(n):
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int):
        pre = pHead
        suc = pHead
        for i in range(k):
            if suc:
                suc = suc.next
            else:
                return None
        while suc:
            pre = pre.next
            suc = suc.next
        else:
            return pre


发表于 2023-05-04 09:23:37 回复(0)
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here
        l = []
        while pHead:
            l.append(pHead)
            pHead = pHead.next 
        if len(l) < k or k == 0:
            return None 
        return l[-k]
发表于 2023-04-26 08:49:06 回复(0)
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here

        # 函数:求链表长度
        def lenth(pHead):
            n = 0
            while pHead:
                n += 1
                pHead = pHead.next
            return n

        # 判断长度是否小于k?
        l = lenth(pHead) 
        if l < k:
            return None
        else:
            n = l - k
            while n:
                pHead = pHead.next
                n -= 1
            return pHead
一个笨方法,只用一个指针
写一个函数:求链表长度
然后调用看是否小于k?
小于就输出none
如果大于的话,先求出长度和k的差值n
走n步,之后就是要输出的内容

发表于 2023-03-08 22:07:51 回复(0)
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here
        total_num = 0
        nh = ListNode(0)
        nh.next = pHead

        while pHead:
            pHead = pHead.next
            total_num += 1
        return_num = total_num - k
        if return_num<0:
            return None
        pHead = nh.next
        for i in range(return_num):
            pHead = pHead.next
        return pHead

发表于 2023-03-02 00:47:15 回复(0)
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pHead ListNode类 
# @param k int整型 
# @return ListNode类
#
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here
        slow =  quick = pHead

        while quick and k != 0:
            quick = quick.next
            k -= 1
        
        while quick:
            slow = slow.next
            quick = quick.next

        return slow if k == 0 else None

发表于 2022-11-27 22:14:27 回复(0)
class Solution:
    def FindKthToTail(self , pHead: ListNode, kint) -> ListNode:
        # write code here
        head=pHead
        box=[]
        while head:
            box.append(head)
            head=head.next
        n=len(box)
        if n>=k and k!=0:
            res=box[-k]
        else:
            res=None
        return res
发表于 2022-11-13 12:21:12 回复(0)
class Solution:
    def FindKthToTail(self , pHead , k ):
        # write code here
        alist = []
        if pHead== None or k==0:
            return ListNode(0).next
        while(pHead!=None):
            alist.append(pHead)
            pHead = pHead.next
        n = len(alist)
        if n>=k:
            return alist[n-k]
        elif n==k:
            return alist[0]
        else :
            return ListNode(0).next
发表于 2022-03-18 17:50:20 回复(0)