方法一:自己的想法+参考力扣
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
res=[]
while head:
res.append(head)
head=head.next
count+=1
return res[-k]
方法二:快慢指针(力扣)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
quick,slow=head,head
for i in range(k):
quick=quick.next
while quick:
quick=quick.next
slow=slow.next
return slow
思路
1.本来我是想要先求出链表的长度,把链表的值存入一个列表res,之后用链表长度减去k值+1做起始位,count为结束位遍历列表res,得到新的列表newarr,但是报错,因为我返回的值不是listNode类型。
看了力扣,直接遍历链表存储链表的结点至列表res[],不用计算链表长度只要直接返回res[-k].
2.第二种方法是参考力扣解答快慢指针。