From 3acd44f653d89c1c8b9198359740c701eaf413d9 Mon Sep 17 00:00:00 2001 From: jaredliw Date: Mon, 12 Jul 2021 17:08:45 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0py=EF=BC=8C=E6=B3=A8=E9=87=8A?= =?UTF-8?q?js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../链表篇/剑指offer22倒数第k个节点.md | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/animation-simulation/链表篇/剑指offer22倒数第k个节点.md b/animation-simulation/链表篇/剑指offer22倒数第k个节点.md index 2666add..13224ca 100644 --- a/animation-simulation/链表篇/剑指offer22倒数第k个节点.md +++ b/animation-simulation/链表篇/剑指offer22倒数第k个节点.md @@ -96,15 +96,43 @@ public: JS Code: ```javascript var getKthFromEnd = function(head, k) { + //特殊情况 if(!head) return head; + //初始化两个指针, 定义指针指向 let pro = head, after = head; + //先移动绿指针到指定位置 for(let i = 0; i < k - 1; i++){ pro = pro.next; } + //两个指针同时移动 while(pro.next){ pro = pro.next; after = after.next; } + //返回倒数第k个节点 return after; }; -``` \ No newline at end of file +``` + +Python Code: + +```python +class Solution: + def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: + # 特殊情况 + if head is None: + return head + # 初始化两个指针, 定义指针指向 + pro = head + after = head + # 先移动绿指针到指定位置 + for _ in range(k - 1): + pro = pro.next + # 两个指针同时移动 + while pro.next is not None: + pro = pro.next + after = after.next + # 返回倒数第k个节点 + return after +``` +