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