题目如下:
解题思路:
本题的思路较为简单:
- 先遍历单向链表并将其尾部指向 head ,将其变为单向环装列表,并记录链表元素个数 count ;
- 之后根据右移次数 k ,在头部开始的第 count-k 个节点处切段链表,该节点的后一个节点就是新的头结点。
代码如下:
/**
* 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 *temp = head;
int count = 1;
//先将单链表转换为环装列表
while(temp->next != NULL){
temp = temp->next;
count++; //记录链表元素个数
}
k = k % count; //k大于元素个数时,只需要处理余数部分
if(k == 0)
return head;
temp->next = head; //将单链表连接成环状列表
//根据右移次数,在对应位置切断环装链表,返回新的表头
temp = head;
for(int i = 1; i < (count-k); i++){
temp = temp->next;
}
ListNode *res = temp->next; //定位到切段环装链表位置的前一个节点
temp->next = NULL; //切段环装链表
return res;
}
};