欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > leetcode 61. Rotate List和86. Partition List

leetcode 61. Rotate List和86. Partition List

2025/7/5 20:46:30 来源:https://blog.csdn.net/weixin_41554427/article/details/148178059  浏览:    关键词:leetcode 61. Rotate List和86. Partition List

目录

61. Rotate List

 86. Partition List


61. Rotate List

代码:

/*** 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* rotateRight(ListNode* head, int k) {if(head == nullptr)return head;if(k == 0)return head;ListNode* cur = head;int count = 0;while(cur){count++;cur = cur->next;}k = k%count;if(k == 0)return head;ListNode *pre = nullptr;cur = head;for(int i = 0;i < count -k;i++){pre = cur;cur = cur->next;}if(pre ==nullptr)return head;pre->next = nullptr;ListNode* newhead = cur;while(cur->next){cur = cur->next;}cur->next = head;return newhead;}
};

 86. Partition List

代码:

/*** 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* partition(ListNode* head, int x) {if(head == nullptr)return nullptr;ListNode* left_dummy = new ListNode(-1,nullptr);ListNode* right_dummy =new ListNode(-1,nullptr);ListNode* leftpre = left_dummy;ListNode* rightpre = right_dummy;ListNode* cur = head;while(cur){if(cur->val < x){leftpre->next = cur;leftpre = cur;}else{rightpre->next = cur;rightpre = cur;}cur = cur->next;}leftpre->next = right_dummy->next;rightpre->next = nullptr;ListNode* ans = left_dummy->next;delete left_dummy;delete right_dummy;return ans;}
};

版权声明:

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

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

热搜词