当前位置:网站首页>[C题目]牛客 链表中倒数第k个结点
[C题目]牛客 链表中倒数第k个结点
2022-07-25 14:44:00 【GLC8866】
思路:标记两个指针aim和cur从pListhead开始,先让前一个指针cur提前挪动k个结点,再同步挪动两个指针,直到前面的cur指针为NULL,aim指针所在位置就是倒数第k个。
(IO型OJ题,可以通过他给的测试用例一步步改进。)
测试用例:
1,{1,2,3,4,5}
5,{1,2,3,4,5}
100,{}
6,{1,2,3,4,5}
0,{1,2,3,4,5}
10,{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}预期输出:
{5}
{1,2,3,4,5}
{}
{}
{}
{11,12,13,14,15,16,17,18,19,20}
struct ListNode* FindKthToTail(struct ListNode* pListHead, int k )
{
if(pListHead==NULL||k==0)//空链表或者k等于0就返回空链表
return NULL;
struct ListNode* aim=pListHead;
struct ListNode* cur=pListHead;
while(k>0)//k表示前指针需要挪动的次数
{
if(cur==NULL)//一旦cur等于空指针必须终止循环
break;
cur=cur->next;
k--;//挪动一次,k减一。
}
if(k>0)//k为正数表示是break出循环的,说明已经超过结点个数,返回整个链表。
return NULL;
while(cur)//最普通的情况,双指针并排挪动,直到cur为NULL。
{
cur=cur->next;
aim=aim->next;
}
return aim;
}
边栏推荐
猜你喜欢

06、类神经网络

【MySQL必知必会】触发器 | 权限管理

45padding不会撑开盒子的情况

Go语言创始人从Google离职

用GaussDB(for Redis)存画像,推荐业务轻松降本60%

I hope some suggestions on SQL optimization can help you who are tortured by SQL like me

Gameframework making games (I)

English语法_不定代词 - other / another

GameFramework制作游戏(二)制作UI界面

Why do China Construction and China Railway need this certificate? What is the reason?
随机推荐
Filters get the data in data; Filters use data in data
35 quick format code
35 快速格式化代码
D2. picking carrots (hard version) (one question per day)
Ssh server rejected password
Flask SSTI injection learning
Practical guide for network security emergency response technology (Qianxin)
优质数对的数目[位运算特点+抽象能力考察+分组快速统计]
[Nuxt 3] (十一) 传送 & 模块
AS查看依赖关系和排除依赖关系的办法
Educational codeforces round 132 (rated for Div. 2) C, d+ac automata
SSH服务器拒绝了密码
Overview of cloud security technology development
Wechat official account official environment online deployment, third-party public platform access
awk从入门到入土(20)awk解析命令行参数
Alibaba cloud installs mysql5.7
用GaussDB(for Redis)存画像,推荐业务轻松降本60%
Gson and fastjson
C language and SQL Server database technology
Gonzalez Digital Image Processing Chapter 1 Introduction