题目描述:
水题,和以前做过一道删除倒数第n个节点类似,点击打开链接,这题思路和做法也差不多,要找到旋转后新的头结点,具体代码如下:
/**
* 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) return head;
ListNode* p = head;
int cnt = 0;
while(p != NULL){
p = p -> next;
cnt++;
}
int k0 = k % cnt;
if(k0 == 0) return head;
ListNode* q = head;
int cnt1 = k0;
while(cnt1 > 0){ // 让q走k个单位,记录最后答案节点(ans)的前缀,方便操作
q = q -> next;
cnt1--;
}
p = head;
while(p != NULL && q != NULL && q -> next != NULL){
p = p -> next;
q = q -> next;
}
ListNode* ans;
if( p != NULL && p -> next != NULL)
ans = p -> next;
if(q != NULL)
q -> next = head;
if(p != NULL)
p -> next = NULL;
return ans;
}
};