python实现链表中倒数第k个结点
2024-08-25 03:08:14
题目描述
输入一个链表,输出该链表中倒数第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
l = []
while head != None:
l.append(head)
head = head.next
if k > len(l) or k < 1:
return
return l[-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 head == None or k == 0:
return None
pAhead = head
pBehind = None
for i in range(0,k-1):
if pAhead.next != None:
pAhead = pAhead.next
else:
return None
pBehind = head
while pAhead.next != None:
pAhead = pAhead.next
pBehind = pBehind.next
return pBehind
最新文章
- tnt_esri.dat Arcgis8.1安装license
- jQuery学习之:Validation表单验证插件
- Sqoop使用手册
- 广义表 Head Tail
- 通过IP的方式建立PSSession
- js动态生成JSON树
- wx.Frame
- magento 获取attribute的所有option
- 这几天有django和python做了一个多用户博客系统(可选择模板)
- vue数据请求
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](五)
- cogs 619. [金陵中学2007] 传话
- Redis出现多线程调用时抛出 [B cannot be cast to java.lang.Long] 异常
- 导出表结构sql语句
- Caused by: java.net.BindException: Address already in use: bind
- 评价指标1--F1值和MSE
- 为订阅内虚拟机批量安装并配置 Microsoft Anti-Malware 扩展
- SaltStack的配置管理--jinja (七)
- servlet request getQueryString 汉字的URI编码如何转码
- csharp: QR Code Barcode