剑指Offer(Python多种思路实现):链表中倒数第k个节点

剑指Offer(Python多种思路实现):链表中倒数第k个节点

面试22题:

题目:链表中倒数第k个节点

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

解题思路一:为了实现只遍历链表一次就能找到倒数第k个节点,我们可以定义两个指针。让第一个指针先向前走k-1步,第二个指针保持不动;从第k步开始,第二个指针也开始从链表的头指针开始遍历。由于两个指针的距离保持在k-1,当第一个指针到达链表的尾节点时,第二个指针刚好到达倒数第k个节点。

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        if not head or k<=0:
            return None
        pAhead=head
        pBehind=None
        for i in range(k-1):
            if pAhead.next:
                pAhead=pAhead.next
            else:
                return None
        pBehind=head
        while pAhead.next:
            pAhead=pAhead.next
            pBehind=pBehind.next
        return pBehind

解题思路二:

def FindKthToTail(self, head, k):
    fast = slow = head
    for _ in range(k):
        if not fast:
            return None
        fast = fast.next
    while fast:
        slow, fast = slow.next, fast.next
    return slow
发布了35 篇原创文章 · 获赞 2 · 访问量 9652

猜你喜欢

转载自blog.csdn.net/weixin_44151089/article/details/104454425
今日推荐