题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

# 创建链表节点类
class NodeList(object):
    def __init__(self,value,next=None) -> None:
        self.value = value
        self.next = next
# 构建单向链表
def builtlinklist(nums):
    if not nums:
        return None
    head = NodeList(nums[0])
    current = head
    for i in range(1,len(nums)):
        current.next = NodeList(nums[i])
        current = current.next
    return head
# 利用快慢指针法寻找倒数K的节点
def getK(head,k):
    fast = slow = head
    for i in range(k):
        fast = fast.next
    while fast:
        fast = fast.next
        slow = slow.next
    return slow
while True:
    try:
        n = int(input())
        numbers = list(map(int,input().split()))
        k = int(input())
        head= builtlinklist(numbers)
        result = getK(head,k)
        print(result.value)
    except:
        break

#单向链表#
全部评论

相关推荐

10-24 11:10
山西大学 Java
若梦难了:哥们,面试挂是很正常的。我大中厂终面挂,加起来快10次了,继续努力吧。
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务