当前位置:网站首页>剑指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;
}
};
边栏推荐
- 关于c语言的调试技巧
- Lightweight AlphaPose
- MATLAB drawing command fimplicit detailed introduction to drawing implicit function graphics
- 第三十三章:图的基本概念与性质
- Do Windows 10 computers need antivirus software installed?
- Doubled and sparse tables
- 网络安全抓包
- In-depth understanding of Golang's Map
- Open the door to electricity "Circuit" (3): Talk about different resistance and conductance
- Letter combination of LeetCode2 phone number
猜你喜欢

6. Unified logging

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

Codeforces Round #605 (Div. 3)

The SSE instructions into ARM NEON

5. Transaction management

Network Security Packet Capture

Detailed introduction to drawing complex surfaces using the plot_surface command

word方框怎么打勾?

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

推开机电的大门《电路》(二):功率计算与判断
随机推荐
Use tencent cloud builds a personal blog
What is Win10 God Mode for?How to enable God Mode in Windows 10?
Detailed explanation of MATLAB drawing function plot
Redis常见面试题
二叉树遍历之后序遍历(非递归、递归)入门详解
Please make sure you have the correct access rights and the repository exists. Problem solved
轻量化AlphaPose
永久更改pip源
Introduction to C language function parameter passing mode
第三十一章:二叉树的概念与性质
Open the door of power and electricity "Circuit" (2): Power Calculation and Judgment
Publish module to NPM should be how to operate?Solutions to problems and mistake
KiCad Common Shortcuts
Do Windows 10 computers need antivirus software installed?
C语言函数参数传递模式入门详解
7.Redis
一篇文章彻底理解Redis的持久化:RDB、AOF
Use libcurl to upload the image of Opencv Mat to the file server, based on two methods of post request and ftp protocol
Redis common interview questions
软件测试基础知识(背)