LeetCode 61. 旋转链表
程序员文章站
2022-05-20 19:10:03
...
/**
* 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) return nullptr;
int len = 0;
ListNode *cur = head, *tail = cur;
while(cur != nullptr){
if(cur->next == nullptr) tail = cur;
cur = cur->next;
len++;
}
k = k%len;
if(!k) return head;
cur = head;
ListNode* pre = nullptr;
for(int i=0;i<len-k;i++){
pre = cur;
cur = cur->next;
}
pre->next = nullptr;
tail->next = head;
return cur;
}
};
上一篇: 230二叉搜索树中第K个小的元素
下一篇: 112路径总和