题解 | #链表中倒数第k个结点#

链表中倒数第k个结点

http://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9

【剑指offer】链表中倒数第K个结点(python)

我的思路是先遍历链表得到链表长度length,同时复制一份链表(不需要复制链表,只需要tmp=pHead,指向一块内存就行),因为遍历后指针指向链表末尾(pHead指针指向末尾,tmp还在开头),然后数tmp链表到第length-k个结点。
链表为空的判定条件和返回值

if pHead is None:

    return None

实现代码

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pHead ListNode类 
# @param k int整型 
# @return ListNode类
#
class Solution:
    '''
    def Clone(self, pHead):
        if not pHead:
            return None
        cloneHead = ListNode(pHead.val)
        cloneHead.next = self.Clone(pHead.next)
        return cloneHead
    '''
    def FindKthToTail(self , pHead , k ):
        # write code here
        count = 0
        if pHead is None:
            return None
        # tmp = self.Clone(pHead)
        tmp = pHead
        while pHead:
            count+=1
            pHead = pHead.next
        if k > count:
            return None
        else:
            for i in range(count - k + 1):
                if i == count - k:
                    return tmp
                else:
                    tmp = tmp.next

太蠢了,这个更简单一些,遍历的时候把结点复制到数组里,直接返回数组倒数第k个点。

# 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 ):
        # write code here
        result=[]
        if pHead is None:
            return None
        while pHead:
            result.append(pHead)
            pHead=pHead.next
        if k<1 or k>len(result):
            return None
        else:
            return result[-k]
全部评论

相关推荐

白火同学:1、简历可以浓缩成一页,简历简历先要“简”方便HR快速过滤出有效信息,再要“历”用有效信息突出个人的含金量。 2、教育背景少了入学时间~毕业时间,HR判断不出你是否为应届生。 3、如果你的平台账号效果还不错,可以把账号超链接或者用户名贴到对应位置,一是方便HR知道你是具体做了什么内容的运营,看到账号一目了然,二是口说无凭,账号为证,这更有说服力。
面试被问期望薪资时该如何...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务