当前位置:网站首页>剑指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;
}
};
边栏推荐
- Based on the matrix calculation in the linear regression equation of the coefficient estimates
- Mysql连接错误解决
- MATLAB绘图函数ezplot入门详解
- 第三十二章:二叉树的存储与遍历
- Actual combat Meituan Nuxt +Vue family bucket, server-side rendering, mailbox verification, passport authentication service, map API reference, mongodb, redis and other technical points
- 1.开发社区首页,注册
- Mysql的锁
- What is Win10 God Mode for?How to enable God Mode in Windows 10?
- How to add a one-key shutdown option to the right-click menu in Windows 11
- 基于矩阵计算的线性回归分析方程中系数的估计
猜你喜欢
随机推荐
General code for pytorch model to libtorch and onnx format
[System Design and Implementation] Flink-based distracted driving prediction and data analysis system
In-depth understanding of Golang's Map
深入理解Golang之Map
Introduction to in-order traversal (non-recursive, recursive) after binary tree traversal
Article pygame drag the implementation of the method
Redis常见面试题
5.事务管理
MATLAB绘图函数plot详解
队列与栈
How to set the win10 taskbar does not merge icons
Mysql之MVCC
IPV4和IPV6是什么?
Happy, 9/28 scene collection
STM32LL library use - SPI communication
Knapsack Problem - Dynamic Programming - Theory
远程连接Ubuntu中的Mysql
LeetCode 2354. 优质数对的数目 二进制01表示和集合之间的转换
MATLAB绘图函数fplot详解
Based on the least squares linear regression equation coefficient estimation