剑指Offer22-链表中倒数第k个节点

剑指Offer22-链表中倒数第k个节点

输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。

例如,一个链表有 6 个节点,从头节点开始,它们的值依次是 1、2、3、4、5、6。这个链表的倒数第 3 个节点是值为 4 的节点。

示例:


给定一个链表: 1->2->3->4->5, 和 k = 2.

返回链表 4->5.

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof

一解

统计链表长度length,计算target = length - k得出答案是第target个节点:


# 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:

        length = 0

        tmp = head

        while tmp != None:

            length += 1

            tmp = tmp.next

        target = length - k

        while target != 0:

            head = head.next

            target -= 1

        return head

二解

使用两个指针formerlatter,距离为k,当latter到达链表结尾时,former为结果:


class Solution:

    def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:

        former, latter = head, head

        # 两个指针相距 k

        for _ in range(k):

            former = former.next

        

        # 两个指针同步移动,直到后一个指针到达结尾

        while former:

            former, latter = former.next, latter.next

        return latter

关闭