链表中倒数第K个结点 牛客网 剑指Offer

链表中倒数第K个结点 牛客网 剑指Offer

  • 题目描述
  • 输入一个链表,输出该链表中倒数第k个结点。
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    #run:33ms memory:5728k
    def FindKthToTail(self, head, k):
        if k<=0 or head == None:
            return None
        p = head
        ret = head
        for i in range(k):
            if p:p = p.next
            else:return None
        while(p):
            p = p.next
            ret = ret.next
        return ret
        
    #run:22ms memory:5852k
    def FindKthToTail2(self, head, k):
        if k<=0 or head == None:
            return None
        else:
            count = 0
            p = head
            ret = head
            while p!=None:
                count = count + 1
                if count > k:
                    ret=ret.next
                p = p.next
            if count < k:
                ret = None
            return ret

 

posted @ 2018-09-13 13:26  vercont  阅读(145)  评论(0编辑  收藏  举报