题目链接https://leetcode-cn.com/leetbook/read/linked-list/f00a2/
思路比较简单 要么在原有链表上进行操作,要么重新建立一个链表。注意K的大小和链表长度之间的关系,小心超时
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k){
if(!head || !k){
return head;
}
int len = 0;
struct ListNode* p = head;
while(p){
len++;
p = p->next;
}
k = k % len;
/*以上步骤是为了防止超时做的预处理*/
if(!k){
return head;
}
struct ListNode*newHead = (struct ListNode*)malloc(sizeof(struct ListNode));
newHead->next = NULL;
struct ListNode *h = newHead;
int res = len-k;
p = head;
struct ListNode *q = head;
while(res){
res--;
q = p;
p = p->next;
}
if(p){
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->next = NULL;
newNode->val = p->val;
h->next = newNode;
h = newNode;
p = p->next;
}
q->next = NULL;
while(p){
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->next = NULL;
newNode->val = p->val;
h->next = newNode;
h = newNode;
p = p->next;
}
h->next = head;
return newHead->next;
}