题目
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
C++解法
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
int getCount(ListNode* head) {
if (!head) return 0;
ListNode * node = head;
int count = 1;
while ((node = node->next) != NULL) ++count;
return count;
}
ListNode* getElement(ListNode* head, int index) {
ListNode * node = head;
while (index != 0 && node) {
node = node->next;
--index;
}
return node;
}
ListNode* getLast(ListNode* head) {
ListNode * node = head;
while (node && node->next) node = node->next;
return node;
}
ListNode* rotateRight(ListNode* head, int k) {
// 计数
int count = getCount(head);
if (count == 0 || (k = k % count) == 0) return head;
ListNode * front_tail = getElement(head, count - k - 1);
ListNode * back_head = front_tail->next;
front_tail->next = NULL;
ListNode * back_tail = getLast(back_head);
back_tail->next = head;
return back_head;
}
};
int main(int argc, const char * argv[]) {
Solution solution;
ListNode * node = new ListNode(1);
node->next = new ListNode(2);
node->next->next = new ListNode(3);
node->next->next->next = new ListNode(4);
node->next->next->next->next = new ListNode(5);
ListNode * node2 = solution.rotateRight(node, 2);
cout << node2->val << endl;
while (node2) {
cout << node2->val << " ";
node2 = node2->next;
}
cout << endl;
return 0;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
网友评论