您的位置:首页 > 教育 > 锐评 > 山东省最新疫情动态及公众健康提示_辽宁省人民政府官网首页_中国最好的营销策划公司_淘宝关键词优化软件

山东省最新疫情动态及公众健康提示_辽宁省人民政府官网首页_中国最好的营销策划公司_淘宝关键词优化软件

2025/3/28 11:47:01 来源:https://blog.csdn.net/weixin_44505472/article/details/146475771  浏览:    关键词:山东省最新疫情动态及公众健康提示_辽宁省人民政府官网首页_中国最好的营销策划公司_淘宝关键词优化软件
山东省最新疫情动态及公众健康提示_辽宁省人民政府官网首页_中国最好的营销策划公司_淘宝关键词优化软件

206. 反转链表 - 力扣(LeetCode)https://leetcode.cn/problems/reverse-linked-list/solutions/551596/fan-zhuan-lian-biao-by-leetcode-solution-d1k2/?envType=study-plan-v2&envId=top-100-liked

常规法

记录前一个指针,当前指针,后一个指针,遍历链表,改变指针的指向。

//c++
/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* reverseList(ListNode* head) {ListNode *pre=nullptr;while(head){ListNode *nex=head->next;head->next=pre;pre=head;head=nex;}return pre;}
};#python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:pre=Nonewhile head:nex=head.nexthead.next=prepre=headhead=nexreturn pre  

递归法 

对于每一个元素的下一个的下一个要指向自己,自己再指向空,递归进去得到头指针。

//c++
/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* reverseList(ListNode* head) {if(!head||!head->next)  return head;ListNode * ne=reverseList(head->next);head->next->next=head;head->next=nullptr;return ne;}
};#python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:if not head or not head.next:return headnew=self.reverseList(head.next)head.next.next=head;head.next=None;return new  

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com