力扣61. 旋转链表

 注意去除重复的轮数

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode() : val(0), next(nullptr) {}
 7  *     ListNode(int x) : val(x), next(nullptr) {}
 8  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 9  * };
10  */
11 class Solution {
12 public:
13     ListNode* rotateRight(ListNode* head, int k) {
14         if (head == nullptr || head -> next == nullptr) {
15             return head;
16         }
17         int len = 1;
18         ListNode *vhead = new ListNode(0, head);
19         ListNode *pre = vhead, *cur = head, *nxt = head -> next, *tail;
20         while(cur = cur -> next) { // 求链表长度并找到尾节点
21             pre = cur;
22             len++;
23         }
24         tail = pre;
25         k %= len;
26         if (k == 0) {
27             return head;
28         }
29         pre = vhead, cur = head;
30         for (int i = 0; i < len - k; ++i) { //将cur定位到len-k的位置
31             pre = cur;
32             cur = nxt;
33             nxt = nxt -> next;
34         }
35         //将len-k及之后的链表插到头部
36         pre -> next = nullptr;
37         tail -> next = head;
38         return cur;
39     }
40 };

 

posted on 2025-03-02 21:57  Coder何  阅读(14)  评论(0)    收藏  举报