第一种解法:采用STL库中的list
1.遍历链表,将节点保存在list当中
2.对list中的节点进行重新的调整,向左旋转一位,即将最后一个元素删除,然后插入到第一个位置,依次处理k个节点
current = v_list.back(); v_list.pop_back(); v_list.push_front(current);
3.list中节点的顺序即为最终的链表顺序,利用list中的节点重新建立链表,返回即可
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == NULL || head->next == NULL || k == 0) return head;
ListNode* current = head;
list<ListNode*> v_list;
while (current != NULL){
v_list.push_back(current);
current = current->next;
}
k %= v_list.size(); //关键
while (k-- > 0){
current = v_list.back();
v_list.pop_back();
v_list.push_front(current);
}
head = NULL;
ListNode* c_head = head;
while (!v_list.empty()){
current = v_list.front();
v_list.pop_front();
if (head == NULL) head = current, c_head = head;
else head->next = current, head = current;
}
current->next = NULL;
return c_head;
}
};
第二种解法:参考这里
1.遍历整个链表,获取链表的长度size,并将链表的尾节点链接到首节点,构成循环单链表
2.去除重复部分:k %= size;
3.第(size-k+1)个节点即为最后的首节点,并将链接向首节点的尾指针指向NULL即可
例如:链表为:1 2 3 k=1
size = 3, 即经过旋转后k个节点后,首节点为第**(3-1+1)=3**个节点
即最终链表为:3 1 2
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == NULL || head->next == NULL || k == 0) return head;
ListNode* current = head;
int list_size = 1; //记录链表的长度
while (current->next != NULL){
list_size++;
current = current->next;
}
current->next = head;
k %= list_size;
k = list_size - k;
current = head;
while (k-- > 1){
current = current->next;
}
head = current->next;
current->next = NULL;
return head;
}
};