剑指offer全集详解python版——链表中倒数第k个结点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41679411/article/details/86483662

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

思路:

经典的双指针。

代码:

# -*- 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 not head:
            return head
        if k<=0:
            return ListNode(0).next
        pNode=head
        p1=head
        p2=head
        for i in range(k-1):
            if p1.next:
                p1=p1.next
            else:
                return p1.next
        while p1.next:
            p1=p1.next
            p2=p2.next
        return  p2

猜你喜欢

转载自blog.csdn.net/weixin_41679411/article/details/86483662
今日推荐