class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class List:
def init_list(self, data):
# 判断是否为空
if len(data) == 0:
return None
else:
# 头结点
head = ListNode(data[0])
# 尾节点
tail = head
# 逐个为 data 内的数据创建结点, 建立链表
for i in data[1:]:
node = ListNode(i)
tail.next = node
tail = node
return head
def print(self, head):
while head:
print(head.val, end="->")
head = head.next
print(None)
a = [2, 3, 6]
l = List()
res = l.init_list(a)
print(res)
l.print(res)
class Solution:
def kthToLast(self, head: ListNode, k: int) -> int:
n = 0
current = head
while current:
n += 1
current = current.next
m = n - k
print(m)
for _ in range(m):
head = head.next
return head.val
head = res
k = 1
print(Solution().kthToLast(head, k))
面试题 02.02. 返回倒数第 k 个节点
最新推荐文章于 2024-10-31 09:58:53 发布