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

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

    1.指针法

     1 class Solution:
     2     def FindKthToTail(self, head, k):        
     3         # write code here
     4         if not head  or k==0 or k<0:  #等号与赋值符号区分
     5             return None
     6         cur=head
     7         for i in range(k-1):
     8             if not cur.next:           #这里必须是cur.next,保证cur是非尾结点,这样cur=cur.next赋值才有效;如果替换成cur,可能把空节点赋给cur
     9                 return None            #此时链表少于k个节点而未判断出来,后面的while条件会出错    
    10             else:
    11                 cur=cur.next
    12                 
    13         slow=head
    14         while cur.next:
    15             cur=cur.next
    16             slow=slow.next
    17         return slow

    2.列表法,消耗空间

    class Solution:
        def FindKthToTail(self, head, k):
            # write code here
            l=[]
            while head!=None:
                l.append(head)
                head=head.next
            if k>len(l) or k<1:
                return
            return l[-k]
    

     今天看到的一句话--“为天地立心,为生民立命,为往圣继绝学,为万世开太平” 

  • 相关阅读:
    hdu 1225大水题
    hdu2102广搜
    hdu1403 赤裸裸的后缀数组
    hdu 1526 poj 1087最大流
    hdu 1557暴力枚举
    hdu 1240广搜
    hdu4416 后缀数组
    hdu1113大水题
    hdu2222赤裸裸的DFA
    hdu4476水题
  • 原文地址:https://www.cnblogs.com/wanrongshu/p/12741030.html
Copyright © 2011-2022 走看看