Title Link: https://leetcode.com/problems/rotate-list/
/* Test instructions: Give a list, rotate the list to the right K position *//** * idea: the right-hand k position, quite with the list from the len-k position truncated, and then * the two linked list exchange position, relink to a linked list * */struct ListNode {in T Val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}};class solution {Public:listnode *rotateright (listnode *head, int k) { if (head = = NULL) return head; Empty table, directly returned ListNode *end; int len = GetLength (head, &end); K%= Len; if (k = = 0) return head; else {//int pre = LEN-K; ListNode *root = new ListNode (0); Root->next = head; ListNode *curr = head; int index = 1; while (Index! = Pre) {index + +; Curr = curr->next; }//At this point Curr refers to the last element of the forward half-linked list//or the last element after the list is rotated End->next = root->next; Root->next = curr->next; Curr->next = NULL; Return root->next; }}//Returns the list length//end to the last node in the list int GetLength (ListNode *head, ListNode **end) {int len = 0; while (head! = NULL) {len + +; *end = head; Head = head->next; } return len; }};
61:rotate list (rotating linked list) "linked list" "Two pointers"