zoukankan      html  css  js  c++  java
  • 剑指offer链表中倒数第k个结点python

    题目描述

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

    思路

    定义2个指针,快指针比慢指针多遍历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
            current = head
            count = k
            while count >0:
                if current:
                    current = current.next
                else:
                    return None
                count-= 1 
            while current:
                head = head.next 
                current = current.next
            return head
  • 相关阅读:
    分布式 and 集群
    时间复杂度



    线性表 & 散列表
    栈 & 队列
    数组 & 链表
    数据结构&算法
    Docket 容器引擎
  • 原文地址:https://www.cnblogs.com/wangzhihang/p/11790739.html
Copyright © 2011-2022 走看看