当前位置:网站首页>剑指offer:反转链表
剑指offer:反转链表
2022-08-02 14:11:00 【超级码力奥】
原题链接https://www.acwing.com/problem/content/description/33/
参考链接:https://www.acwing.com/solution/content/6583/ (有动画)
y总:https://www.acwing.com/solution/content/743/
一个pre指针,保留前继节点,一个cur,指向当前节点,一个next,指向下一个节点。
每次:
next保存cur的下一个节点
cur的next指向pre
向后移动一位:pre移到cur,cur移动next
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
ListNode* reverseList(ListNode* head) {
// 记录前驱节点
ListNode* pre = nullptr;
auto cur = head;
while(cur)
{
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
递归:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL) return NULL;
if(head->next == NULL) return head;
ListNode* p = head;
// 先找到最后一个节点
while(p->next->next != NULL)
{
p = p->next;
}
// 新建一个
ListNode* new_head = p->next;
p->next = NULL;
ListNode* p2 = new_head;
while(1)
{
p = head;
if(p->next == NULL)
{
p2->next = p;
break;
}
while(p->next->next)
{
p = p->next;
}
p2->next = p->next;
p->next = NULL;
p2 = p2->next;
}
return new_head;
}
};
边栏推荐
- Spark及相关生态组件安装配置——快速回忆
- Codeforces Round #624 (Div. 3)
- 推开机电的大门《电路》(二):功率计算与判断
- Yolov5 official code reading - prior to transmission
- LeetCode 2343. 裁剪数字后查询第 K 小的数字 暴力+语法考察
- Article pygame drag the implementation of the method
- Win11 keeps popping up User Account Control how to fix it
- Codeforces Round #624 (Div. 3)
- SQL的通用语法和使用说明(图文)
- Detailed explanation of MATLAB drawing function fplot
猜你喜欢

SQL的通用语法和使用说明(图文)

Exotic curiosity-a solution looking - bit operations

TCP三次握手、四次挥手

Redis common interview questions

How to add a one-key shutdown option to the right-click menu in Windows 11

6.统一记录日志

基于最小二乘法的线性回归分析方程中系数的估计

What should I do if the Win10 system sets the application identity to automatically prompt for access denied?

Codeforces Round #605 (Div. 3)

5.事务管理
随机推荐
Win10 computer can't read U disk?Don't recognize U disk how to solve?
pygame图像连续旋转
第二十六章:二维数组
第三十一章:二叉树的概念与性质
What is Win10 God Mode for?How to enable God Mode in Windows 10?
Software Testing Basics (Back)
轻量化AlphaPose
LeetCode 2354. 优质数对的数目 二进制01表示和集合之间的转换
flink+sklearn——使用jpmml实现flink上的机器学习模型部署
pygame拖动条的实现方法
Mysql的锁
Knapsack Problem - Dynamic Programming - Theory
Win11电脑一段时间不操作就断网怎么解决
How to simulate 1/3 probability with coins, and arbitrary probability?
5.事务管理
【STM32学习1】基础知识与概念明晰
Please make sure you have the correct access rights and the repository exists. Problem solved
Configure clangd for vscode
Doubled and sparse tables
4. Publish Posts, Comment on Posts