2024每日刷题(114)
Leetcode—61. 旋转链表
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* rotateRight(ListNode* head, int k) {
if(!head || head->next == nullptr || k == 0) {
return head;
}
ListNode* tail = head;
int len = 1;
for(; tail->next; tail = tail->next) {
len++;
}
// 成环
tail->next = head;
int t = len - k % len;
for(int i = 0; i < t; i++) {
tail = tail->next;
}
ListNode* newNode = tail->next;
// 断链
tail->next = nullptr;
return newNode;
}
};
运行结果
C语言实现代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k) {
if(!head || head->next == NULL || k == 0) {
return head;
}
int lcn = 0;
struct ListNode* p = head;
struct ListNode* q = p;
while(p) {
lcn++;
q = p;
p = p->next;
}
q->next = head;
int cnt = lcn - k % lcn - 1;
p = head;
while(cnt--) {
p = p->next;
}
q = p->next;
p->next = NULL;
return q;
}
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!