剑指offer–链表中倒数第k个结点
一、前言
最近开始刷剑指offer,记录一下。牛客网在线编程板块的剑指offer专区。
牛客网剑指offer:传送门
或者点击下方链接。
https://www.nowcoder.com/ta/coding-interviews
二、题目描述
输入一个链表,输出该链表中倒数第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
# 快慢指针
firstPoint=head
secondPoint=head
for i in range(k):
if firstPoint == None:
return None
firstPoint = firstPoint.next
while firstPoint !=None:
firstPoint=firstPoint.next
secondPoint=secondPoint.next
return secondPoint
def printChain(node):
while node:
print(node.val)
node=node.next
if __name__ == '__main__':
s=Solution()
l1 = ListNode(1)
l2 = ListNode(2)
l3 = ListNode(3)
l4 = ListNode(4)
l5 = ListNode(5)
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
l5.next = None
print(printChain(l1))
print(s.FindKthToTail(l1,3))