//先形成环形链表,然后找到新的头和尾,再断开环形链表
struct ListNode* rotateRight(struct ListNode* head, int k) {
if (head == NULL || head->next == NULL || k == 0) return head;
int len = 1;
struct ListNode* p = head;
while (p->next!= NULL) {
p = p->next;
len++;
}
k = k % len;
p->next = head;
k = len - k;
while (k--) {
p = p->next;
}
struct ListNode* new_head = p->next;
p->next = NULL;
return new_head;
}
struct ListNode* rotateRight(struct ListNode* head, int k) {
if (head == NULL || head->next == NULL || k == 0) {
return head;
}
int len = 1;
struct ListNode* p = head;
while (tail ->next!= NULL) {
tail = tail->next;
len++;
}//因为要找到最后一个结点而不是空结点切要记录链表长度,所以将len初始化为1,
//while里面的条件为tail->next
k = k % len;
if (k == 0) return head;
k = len - k-1;//新的头结点的前一个结点即尾结点所以要-1
struct ListNode* new_tail = head;
while (k--) {
new_tail = new_tail->next;
}
struct ListNode* new_head = new_tail->next;
new_tail->next = NULL;
tail->next = head;//旧的尾结点指向NULL,所以要重新连接
return new_head;
}