LeetCode 61旋转链表-中等
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 61旋转链表-中等
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你一個鏈表的頭節點 head ,旋轉鏈表,將鏈表每個節點向右移動 k 個位置。
輸入:head = [1,2,3,4,5], k = 2
輸出:[4,5,1,2,3]
輸入:head = [0,1,2], k = 4
輸出:[2,0,1]
提示:
鏈表中節點的數目在范圍 [0, 500] 內 -100 <= Node.val <= 100 0 <= k <= 2 * 10^9代碼如下:
/*** 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 || head->next==nullptr || k==0) return head;int n = 1;ListNode *pre = head;while(pre->next){pre = pre->next;n++;}int add = n-k%n;if (add==n) return head;pre->next = head;while(add--){pre = pre->next;}ListNode *cur = pre->next;pre->next = nullptr;return cur;} };總結
以上是生活随笔為你收集整理的LeetCode 61旋转链表-中等的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 24两两交换链表中的节
- 下一篇: 微软高管暗示 Copilot(原 Bin