当前位置:网站首页>链表中关于快慢指针的oj题
链表中关于快慢指针的oj题
2022-07-28 05:18:00 【zhengyawen666】
题目一:
给定一个头结点为 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
leetcode链接:力扣
解题思路:设定两个指针,一个是快指针,一个是慢指针。保持快指针的速度是慢指针的两倍,这样当快指针走到末尾的时候,慢指针刚好走到中间。返回慢指针。
如图:

需要注意的是分奇偶讨论,while循环结束的条件有所不同。
代码:
class Solution {
public:
ListNode* middleNode(ListNode* head) {
struct ListNode*slow=head,*fast=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
};题目二:求倒数第k个结点
题目描述:
输入一个链表,输出该链表中倒数第k个结点。
leetcode链接:链表中倒数第k个结点_牛客题霸_牛客网
思路:由于是求倒数第k个结点,因此就是求从尾结点开始倒数k-1步数的那个结点。可以定义两个指针。一个指针先走k-1步,另一个指针再开始走。等先走的指针走到了尾结点的时候,返回另一个指针就是要求得结点。
如图:
代码:
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
ListNode*slow=pListHead;
ListNode*fast=pListHead;
while(--k)//走k-1步
{if(fast==NULL)
return NULL;
//如果k大于链表的长度 直接返回空
fast=fast->next;
}
while(fast->next)//fast走到null结束
{
fast=fast->next;
slow=slow->next;
}
return slow;
}
};
边栏推荐
- 24小时内的时间段无交叉
- BigDecimal 进行四舍五入 四舍六入和保留两位小数
- ssm项目快速搭建项目配置文件
- URL 形式
- Framework step by step easy-to-use process
- openjudge:统计数字字符个数
- openjudge:万年历
- When using deep learning training image, the image is too large for segmentation training prediction
- Arrangement of main drawings of the latest 54 papers of eccv22
- Fusiongan code learning (I)
猜你喜欢

Framework step by step easy-to-use process

Review of metallurgical physical chemistry ---- gas solid reaction kinetics

How Visio accurately controls the size, position and angle of graphics

Distillation model diagram

Idea uses dev tool to realize hot deployment

Advanced multi threading: the underlying principle of synchronized, the process of lock optimization and lock upgrade

论文模型主图范例

CentOS7安装MySQL5.7

IDEA配置 service(Run Dashboard) 服务,多模块同时启动

ECCV22 最新54篇论文主图整理
随机推荐
多线程进阶:锁的策略
ssm项目快速搭建项目配置文件
VMware Workstation 与 Device/Credential Guard 不兼容。禁用 Device/Credential Guard
(dark horse) MySQL beginner advanced notes (blogger lazy dog)
sql 查询list时两次的数据不一致,自动加上了limit
regular expression
lamda 获取当前循环数,AtomicInteger
使用深度学习训练图像时,图像太大进行切块训练预测
Openjudge: filter extra spaces
图像增强评价指标学习之——结构相似性SSIM
Idea configures the service (run dashboard) service, and multiple modules are started at the same time
BeanUtils.copyProperties无法复制不同List集合问题解决 Lists.transform函数
Edge calculation kubeedge+edgemash
CentOS7安装MySQL5.7
Pytorch uses hook to get feature map
顺序表oj题目
Advanced multi threading: the underlying principle of synchronized, the process of lock optimization and lock upgrade
Writing methods of scientific research papers: add analysis and discussion in the method part to explain their contributions and differences
The way of deep learning thermodynamic diagram visualization
openjudge:找出全部子串位置