当前位置:网站首页>剑指 Offer 22. 链表中倒数第k个节点
剑指 Offer 22. 链表中倒数第k个节点
2022-06-30 05:23:00 【Grayson Zhang】
题目描述
输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。
例如,一个链表有 6 个节点,从头节点开始,它们的值依次是 1、2、3、4、5、6。这个链表的倒数第 3 个节点是值为 4 的节点。
示例:
给定一个链表: 1->2->3->4->5, 和 k = 2.
返回链表 4->5.
题解
遍历两遍,第一遍统计链表总长度,求的倒数节点的正向位置
第二遍,找到节点
1. python
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
cur = head
count = 0
while cur:
count += 1
cur = cur.next
cur = head
count -= k
while count:
cur = cur.next
count -= 1
return cur

2. C语言
struct ListNode* getKthFromEnd(struct ListNode* head, int k){
struct ListNode *cur = head;
int count = 0;
while (cur != NULL) {
count += 1;
cur = cur -> next;
}
cur = head;
count -= k;
while (count != 0) {
count -= 1;
cur = cur -> next;
}
return cur;
}

3.C++
和C一样,就改了一个变量声明
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode *cur = head;
int count = 0;
while (cur != NULL) {
count += 1;
cur = cur -> next;
}
cur = head;
count -= k;
while (count != 0) {
count -= 1;
cur = cur -> next;
}
return cur;
}
};

边栏推荐
猜你喜欢

【VCS+Verdi聯合仿真】~ 以計數器為例

14x1.5cm竖向标签有点难,VFP调用BarTender来打印

【 VCS + Verdi joint simulation】 ~ Taking Counter as an Example

Vfpbs uploads excel and saves MSSQL to the database
![[notes] unity webgl input Chinese](/img/f7/805f510ff691227b4c2b529cc1099a.jpg)
[notes] unity webgl input Chinese

旋转框目标检测mmrotate v0.3.1 训练DOTA数据集(二)

Intellj idea jars projects containing external lib to other project reference methods - jars

pytorch中常用损失函数总结

Redistemplate common method summary

企事业单位源代码防泄露工作该如何进行
随机推荐
2021-10-31
Unity shortcut key
PWN入门(2)栈溢出基础
产生 BUG 测试人员需要自己去分析原因吗?
Array pointers and pointer arrays
Responding with flow layout
【LeetCode】Easy | 232. Using stack to realize queue (pure C manual tearing stack)
Unity scroll view element drag and drop to automatically adsorb centering and card effect
QT connecting external libraries
How can the international trading platform for frying US crude oil guarantee capital security?
Chapter 12 pipeline monitoring of OpenGL super classic (version 7)
Unity3d position the model, rotate, drag and zoom around the model to obtain the center point of the model
MinGW-w64下载文件失败the file has been downloaded incorrectly!
Summary of common loss functions in pytorch
Nestjs配置静态资源,模板引擎以及Post示例
Nestjs入门和环境搭建
Go Land no tests were Run: FMT cannot be used. Printf () & lt; BUG & gt;
Vfpbs uploads excel and saves MSSQL to the database
Another download address for typro
Installation and getting started with pytoch