代码实现:
方法一:在原链表中找到旋转之后的首尾,改变指向
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* rotateRight(struct ListNode *head, int k) { if (k == 0 || head == NULL || head->next == NULL) { return head; } int n = 1; struct ListNode *p = head; while (p->next != NULL) { p = p->next; n++; } int add = n - k % n; if (add == n) { return head; } p->next = head; while (add--) { p = p->next; } struct ListNode *ret = p->next; p->next = NULL; return ret; }
方法二:反转链表
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ // 反转链表 struct ListNode* nizhi(struct ListNode *head) { if (head == NULL || head->next == NULL) { return head; } struct ListNode *tail = head->next; struct ListNode *new_head = nizhi(head->next); head->next = tail->next; tail->next = head; return new_head; } struct ListNode* rotateRight(struct ListNode *head, int k) { if (head == NULL || head->next == NULL || k == 0) { return head; } int len = 0; struct ListNode *p = head; while (p) { len++; p = p->next; } int n = k % len; if (n == 0) { return head; } head = nizhi(head); struct ListNode *h = head, *p1 = head; struct ListNode *p2 = head, *p3; while (n - 1) { p2 = p2->next; n--; } p3 = p2->next; p2->next = NULL; h = nizhi(h); p3 = nizhi(p3); p1->next = p3; return h; }