1.我只想到了一个最直白的办法┭┮﹏┭┮
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def kthToLast(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: int
"""
length=0
n1=head
num=[]
while(n1):
num.append(n1.val)
length+=1
n1=n1.next
return num[length-k]
就是把所有的值放到一个数组里面,直接取对应的值
2.看解题,好嘛,他们用的是双指针,真的聪明
两个指针p,q,先让其中一个,比如p向前走k步,他们俩之间恰好差了k步,然后p,q一起走,当p走到尾部的时候,q恰好走到倒数第k个。看来双指针在链表里面用的很多啊,有个大佬总结了一下双指针的用法。
https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/solution/tu-jie-shuang-zhi-zhen-you-zou-cchao-guo-100de-ti-/
class Solution(object):
def kthToLast(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: int
"""
n1=head
n2=head
while(k):
n2=n2.next
k-=1
while(n2):
n1=n1.next
n2=n2.next
return n1.val
内存消耗都差不多,但是笨办法的用时短一些诶。