当前位置:网站首页>剑指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;
}
};
边栏推荐
- Win11 computer off for a period of time without operating network how to solve
- Mysql连接错误解决
- 使用 腾讯云搭建一个个人博客
- Mysql connection error solution
- 第二十九章:树的基本概念和性质
- 基于矩阵计算的线性回归分析方程中系数的估计
- STM32LL库使用——SPI通信
- [System Design and Implementation] Flink-based distracted driving prediction and data analysis system
- Open the door of power and electricity "Circuit" (2): Power Calculation and Judgment
- GMP scheduling model of golang
猜你喜欢
What should I do if the Win10 system sets the application identity to automatically prompt for access denied?
In-depth understanding of Golang's Map
二叉树遍历之后序遍历(非递归、递归)入门详解
2.登录退出,登录状态检查,验证码
Codeforces Round #605 (Div. 3)
6. Unified logging
[System Design and Implementation] Flink-based distracted driving prediction and data analysis system
Introduction to C language function parameter passing mode
golang之GMP调度模型
yolov5官方代码解读——前向传播
随机推荐
pytorch模型转libtorch和onnx格式的通用代码
C语言函数参数传递模式入门详解
Letter combination of LeetCode2 phone number
cmake配置libtorch报错Failed to compute shorthash for libnvrtc.so
MATLAB绘图函数ezplot入门详解
4. Publish Posts, Comment on Posts
Summarize computer network super comprehensive test questions
1. Development community homepage, register
二叉树创建之层次法入门详解
MATLAB绘图函数plot详解
如何用硬币模拟1/3的概率,以及任意概率?
Use libcurl to upload the image of Opencv Mat to the file server, based on two methods of post request and ftp protocol
Open the door to electricity "Circuit" (3): Talk about different resistance and conductance
3. User upload avatar
专硕与学硕
Mapreduce环境详细搭建和案例实现
Yolov5 official code reading - prior to transmission
cmake configure libtorch error Failed to compute shorthash for libnvrtc.so
pygame拖动条的实现方法
Daily - Notes