algorithm-base/animation-simulation/链表篇/剑指offer22倒数第k个节点.md

139 lines
4.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [ Offer 22. k](https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/)
k11612345634
n
1038k
K-1K-1K
![](https://img-blog.csdnimg.cn/img_convert/506c4d70f4c50c66994711c8506462a8.gif)
****
Java Code:
```java
class Solution {
public ListNode getKthFromEnd (ListNode head, int k) {
//特殊情况
if (head == null) {
return head;
}
//初始化两个指针
ListNode pro = new ListNode(-1);
ListNode after = new ListNode(-1);
//定义指针指向
pro = head;
after = head;
//先移动绿指针到指定位置
for (int i = 0; i < k-1; i++) {
pro = pro.next;
}
//两个指针同时移动
while (pro.next != null) {
pro = pro.next;
after = after.next;
}
//返回倒数第k个节点
return after;
}
}
```
C++ Code:
```cpp
class Solution {
public:
ListNode * getKthFromEnd(ListNode * head, int k) {
//特殊情况
if (head == nullptr) {
return head;
}
//初始化两个指针
ListNode * pro = new ListNode(-1);
ListNode * after = new ListNode(-1);
//定义指针指向
pro = head;
after = head;
//先移动绿指针到指定位置
for (int i = 0; i < k-1; i++) {
pro = pro->next;
}
//两个指针同时移动
while (pro->next != nullptr) {
pro = pro->next;
after = after->next;
}
//返回倒数第k个节点
return after;
}
};
```
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;
};
```
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
```