码迷,mamicode.com
首页 > 其他好文 > 详细

链表中倒数第k个节点

时间:2018-08-28 13:05:10      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:col   ext   一个   节点   nbsp   tail   turn   one   find   

题目描述

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

思路

注意,看清楚,是输出节点,而不是输出节点值

可以先求出链表总长度,然后正向遍历得到第n个节点

解答

class Solution:
    def FindKthToTail(self, head, k):
        count = 0
        p = head
        while p:
            count += 1
            p = p.next
        if count < k:
            return None
        number = count-k+1
        new_count = 0
        pHead = head
        while pHead:
            new_count += 1
            if new_count == number:
                return pHead
            pHead = pHead.next

 

链表中倒数第k个节点

标签:col   ext   一个   节点   nbsp   tail   turn   one   find   

原文地址:https://www.cnblogs.com/yqpy/p/9547405.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!