文章目录
双指针
同时初始化两个指针指向head
,接着先遍历node1
,并记录下当前遍历到的节点个数记为n
,当
n
>
k
n > k
n>k 时,开始遍历node2
,注意这里要先判断是否遍历node2
,再遍历node1
,这样当node1
遍历完毕时就能跳出循环
# 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:
if not head.next:
return head
node1 = head # 前节点
node2 = head # 后节点
n = 1 # 用于记录node1当前遍历的节点数
while node1:
# 当遍历个数超过k时,第二个指针开始遍历
if n > k:
node2 = node2.next
node1 = node1.next
n += 1
return node2