当前位置:网站首页>剑指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;
}
};
边栏推荐
- 如何用硬币模拟1/3的概率,以及任意概率?
- Ubuntu通过apt安装Mysql
- pygame图像连续旋转
- win10 system update error code 0x80244022 how to do
- 2.登录退出,登录状态检查,验证码
- pygame拖动条的实现方法
- What is Win10 God Mode for?How to enable God Mode in Windows 10?
- cmake配置libtorch报错Failed to compute shorthash for libnvrtc.so
- Summarize computer network super comprehensive test questions
- TCP三次握手、四次挥手
猜你喜欢

6. Unified logging

How to solve Win11 without local users and groups

Detailed introduction to drawing complex surfaces using the plot_surface command

Open the door of electricity "Circuit" (1): voltage, current, reference direction

第二十七章:时间复杂度与优化

Installation and configuration of Spark and related ecological components - quick recall

推开机电的大门《电路》(三):说说不一样的电阻与电导

Mysql connection error solution

Happy, 9/28 scene collection

2.登录退出,登录状态检查,验证码
随机推荐
golang之GMP调度模型
Win10 Settings screen out from lack of sleep?Win10 set the method that never sleep
cmake configure libtorch error Failed to compute shorthash for libnvrtc.so
MATLAB绘图函数plot详解
STM32LL库——USART中断接收不定长信息
编译error D8021 :无效的数值参数“/Wextra” cl command line error d8021 invalid numeric argument ‘/wextra‘
深入理解Golang之Map
将SSE指令转换为ARM NEON指令
第二十九章:树的基本概念和性质
模板系列-二分
第三十一章:二叉树的概念与性质
6. Unified logging
SQL的通用语法和使用说明(图文)
质数相关问题-小记
KiCad Common Shortcuts
STM32LL library - USART interrupt to receive variable length information
推开机电的大门《电路》(一):电压,电流,参考方向
第二十八章:解题技巧
软件测试基础知识(背)
LeetCode 2343. 裁剪数字后查询第 K 小的数字 暴力+语法考察