【剑指offer】17_链表中倒数第k个结点

题目:

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


关于链表和数组:

https://blog.csdn.net/Shuffle_Ts/article/details/95055467

 

1、创建一个新数组,遍历链表中的结点,将数值存入数组中。输出数组中-k下标对应的值即可

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 is not None:
            l.append(head)
            head = head.next
        if k > len(l) or k <= 0: # 没有倒数第0个的说法,所以是k<=0
            return None
        return l[-k]

 

2、Python 设置两个指针,p1,p2,先让p2走k-1步,然后再一起走,直到p2为最后一个 时,p1即为倒数第k个节点

class Solution2:
    def FindKthToTail2(self, head, k):
        if head is None or k <= 0: # 没有倒数第0个的说法,所以是k<=0
            return None
        # write code here
        p1 = head
        p2 = head
        while k > 1: # p2到第k-1个结点 停止
            if p2.next is not None:
                p2 = p2.next
                k -= 1
            else:
                return None
        while p2.next is not None: # p2到最后一个结点停止
            p2 = p2.next
            p1 = p1.next
        return p1

 

 

 

posted @ 2020-02-11 19:50  RebeccaG  阅读(91)  评论(0编辑  收藏  举报