当前位置:网站首页>剑指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;
}
};
边栏推荐
猜你喜欢

Summarize computer network super comprehensive test questions

Win11电脑一段时间不操作就断网怎么解决

4. Publish Posts, Comment on Posts

MATLAB绘图函数ezplot入门详解

Use tencent cloud builds a personal blog

第二十五章:一文掌握while循环

IPV4和IPV6是什么?

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

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

MATLAB图形加标注的基本方法入门简介
随机推荐
为vscode配置clangd
Mapreduce环境详细搭建和案例实现
Flink + sklearn - use JPMML implement flink deployment on machine learning model
What should I do if the Win10 system sets the application identity to automatically prompt for access denied?
Daily - Notes
jest test, component test
二叉排序树与 set、map
第三十章:普通树的存储和遍历
推开机电的大门《电路》(一):电压,电流,参考方向
Do Windows 10 computers need antivirus software installed?
Spark及相关生态组件安装配置——快速回忆
LeetCode 2353. 设计食物评分系统 维护哈希表+set
Failed to install using npx -p @storybook/cli sb init, build a dedicated storybook by hand
Please make sure you have the correct access rights and the repository exists. Problem solved
测试用例练习
Redis的线程模型
Use tencent cloud builds a personal blog
General syntax and usage instructions of SQL (picture and text)
3.用户上传头像
使用libcurl将Opencv Mat的图像上传到文件服务器,基于post请求和ftp协议两种方法