Old Wei wins the offer to take you to learn --- Brush title series (the reciprocal of the k-th node 14. The linked list)

14. A linked list node k-th countdown

problem:

Input a linked list, the linked list output reciprocal k-th node.

solve:

thought:

Python is provided two pointers, p1, p2, p2 let down step k-1, then go together until p2 is the last one, p1 is the penultimate node k

python code

# -*- 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 head==None or k<=0:
            return None
        current=head
        while k>0:
            if current!=None:
                current=current.next
                k-=1
            else:
                return None
            
        backup=head
        while(current!=None):
            current=current.next
            backup=backup.next
        return backup
Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/104902966