Python剑指>>输入一个链表,输出该链表中倒数第k个结点。

题目描述

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

 

1.先遍历得出链表长度,也就是节点数,在遍历第count-k个节点,注意小于count-k<0的情况

 

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        if k<=0 or head==None:
            return None
        count=0
        p=head
        while p!=None:
            count=count+1
            p=p.next
        if count

2.请求一个列表,直接查询列表,见代码 

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

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]

 

你可能感兴趣的:(剑指Offer)