链表中倒数第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

 

相关文章:

  • 2021-04-23
  • 2021-12-12
  • 2021-08-13
  • 2021-05-26
  • 2021-06-30
  • 2021-11-24
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-02
  • 2021-10-31
  • 2022-02-08
  • 2021-07-23
  • 2022-12-23
相关资源
相似解决方案