当前位置:网站首页>LeetCode206——反转链表
LeetCode206——反转链表
2022-07-22 10:29:00 【Zheyuan Zou】
一道经典的数据结构初学者问题,主要考察指针的修改和用法:
就像题目中进阶要求所说的那样,这道题有两种解法:迭代和递归。但其实它们的核心操作都是一样的,就是代码中修改指针的部分,当然这题需要一前一后两个指针跟随着一步步将链表逆置。
下面贴出我的代码,首先是递归写法:
// recursive method
void recursive(ListNode*& Ahead, ListNode*& Follow)
{
if(Ahead == nullptr)
return;
/*store the Ahead->next pointer*/
ListNode* Tmp = Ahead->next;
/*modify the pointer*/
Ahead->next = Follow;
Follow = Ahead;
Ahead = Tmp;
recursive(Ahead, Follow);
}
// start of the main function
ListNode* reverseList(ListNode* head)
{
if(head == nullptr)
return head;
/*recursive method*/
ListNode* Ahead = head->next;
ListNode* Follow = head;
/*set the first node's next to nullptr*/
Follow->next = nullptr;
recursive(Ahead, Follow);
return Follow;
}
其次是迭代的写法:
ListNode* reverseList(ListNode* head)
{
if(head == nullptr)
return head;
/*iterative method*/
ListNode* Ahead = head->next;
ListNode* Follow = head;
/*set the first node's next to nullptr*/
Follow->next = nullptr;
while(Ahead)
{
/*store the next pointer*/
ListNode* Tmp = Ahead->next;
Ahead->next = Follow;
Follow = Ahead;
Ahead = Tmp;
}
return Follow;
}
可以看到核心部分代码都是下面这几步,当然还有不要忘记将第一个结点的next指针指向nullptr:
ListNode* Tmp = Ahead->next;
Ahead->next = Follow;
Follow = Ahead;
Ahead = Tmp;
边栏推荐
- 她力量系列三丨把握当下,坚持热爱,与食物图像识别结缘的科研之路
- mysql查询blob
- How to deal with DNS hijacked? Five ways to deal with it
- 信号量实现同步互斥经典案例
- The setting of node.master and node.data in the production environment of the introduction to elastic search (3)
- The relationship between WLAN, Wi Fi and 802.11
- dns被劫持有什么现象?DNS是什么 dns被劫持了如何解决
- Flask Cross - Domain
- 求N!后面有多少个0
- 网页被劫持了该怎么办?dns被劫持如何修复?网页劫持介绍
猜你喜欢
What should I do if the web page is hijacked? How to repair DNS hijacked? Introduction to web hijacking
百度快照劫持是什么意思?如何解决百度快照被劫持、百度劫持
《强化学习周刊》第39期:近似最优深度、多智能体广义、角色动画强化学习
YOLO v1、v2、v3
蓝桥杯省赛训练营——常用STL
【C】从内存出发理解C语言变量作用域与生命周期
基于canny的亚像素的Devernay Algorithm
蓝桥杯省赛训练营——日期的计算
Comment le détournement de DNS peut - il être parfaitement réparé? Comment résoudre le problème du détournement de DNS
【C】二叉树遍历的递归与非递归写法
随机推荐
The database is encapsulated by queryrunner simulation
将一些转义字符替换为指定标准的字符
生成删除数据库所有表的外检脚本
Getting started with elastic search: installation and configuration of elastic search (I)
Nc54 sum of three numbers
她力量系列八丨陈丹琦:我希望女生能够得到更多的机会,男生和女生之间的gap会逐渐不存在的
求幂的位数,求阶乘的位数
How to deal with DNS hijacking, DNS hijacking, and DNS hijacking solutions
CPU亲和力
[reading notes] MySQL architecture and storage engine
网页被劫持了该怎么办?dns被劫持如何修复?网页劫持介绍
《预训练周刊》第38期: Transformer、BERT结构优化
Plug in installation of elastic search getting started (5)
Core concepts of elastic search learning Introduction (4)
spark中使用Accumulator累加器使用和注意事项
Flask cross domain
dns 劫持什么意思、dns 劫持原理及几种解决方法
求N!后面有多少个0
【C】从内存出发理解C语言变量作用域与生命周期
Introduction to machine learning: support vector machine-6