剑指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]

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

猜你喜欢

转载自www.cnblogs.com/wanrongshu/p/12741030.html