当前位置: 首页> 房产> 建筑 > 反转链表-力扣

反转链表-力扣

时间:2025/7/14 21:53:36来源:https://blog.csdn.net/why_12134/article/details/139158877 浏览次数:0次

该题使用虚拟头节点来做在思考的时候稍微有点复杂,但与从头节点开始,利用一个cur节点来反转流程是一样的,只需将dummyhead->next 当作是 cur 来操作即可。代码如下:

/*** 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 * dummyhead = new ListNode(0);ListNode * pre = NULL;ListNode * tmp = NULL;dummyhead->next = head;while(dummyhead->next != NULL){tmp = dummyhead->next->next;dummyhead->next->next = pre;pre = dummyhead->next;dummyhead->next = tmp;}return pre;}
};

不适用虚拟头节点的代码如下:

/*** 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 = NULL;ListNode * tmp = NULL;ListNode * cur = head;while(cur != NULL){tmp = cur->next;cur->next = pre;pre = cur;cur = tmp;}return pre;}
};

使用迭代的写法,代码如下:

class Solution {
public:ListNode* reverse(ListNode* pre, ListNode* cur){if(cur == NULL){return pre;}ListNode* tmp = cur->next;cur->next = pre;return reverse(cur,tmp);}ListNode* reverseList(ListNode* head) {return reverse(NULL,head);}
};
关键字:反转链表-力扣

版权声明:

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

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

责任编辑: