Given a list, rotate the list to the right by K places, where k is non-negative.
For example:
Given1->2->3->4->5->NULL
Andk = 2
,
Return4->5->1->2->3->NULL
.
I was wondering why this question was "right-handed", not "left-handed? So what is the difference between left-hand and right-hand? First, let's talk about my solution ideas:
First, connect the head and tail of the linked list to form a ring, and then rotate by moving the pointer. After rotating to the correct position, the ring is broken into a linked list and then returned.
According to this idea, the "left-hand" is much simpler, because the linked list is a one-way linked list instead of a two-way linked list. The left-hand code is implemented as follows:
C ++ codeListnode * rotateleft (listnode * head, int K) {If (! Head) return NULL; listnode * curr = head; while (curr-> next) curr = curr-> next; // find the end node curr-> next = head in this loop; // at this time, curr points to the end node and connects the end to the header for (INT I = 0; I <K; ++ I) curr = curr-> next; // left-hand K step head = curr-> next; // disconnect the ring into a linked list curr-> next = NULL; return head ;}
So what if we follow this idea to achieve right-hand? A opportunistic method is that the right-hand K step is actually the left-hand step.count - k % count
(Count refers to the length of the entire linked list ). The code is implemented as follows:
C++ code ListNode *rotateRight(ListNode *head, int k) { if (!head) return head; if (k ==0) return head; int count = 1; ListNode *curr; for (curr = head; curr->next != NULL; curr = curr->next) ++count; curr->next = head; for (int i = 0; i < count - k % count; ++i) curr = curr->next; head = curr->next; curr->next = NULL; return head; }
The time complexity of the preceding algorithm isO(N), The space complexity isO(1) You can take some measures to sacrifice space performance and remove the second loop in exchange for a certain time performance:
C++ code ListNode *rotateRight(ListNode *head, int k) { if (!head ) return head; if (k == 0) return head; vector<ListNode *> nodeVec; for (ListNode *curr = head; curr != NULL; curr = curr->next) nodeVec.push_back(curr); int listLen = nodeVec.size(); k %= listLen; if (k == 0) return head; nodeVec[listLen - 1]->next = nodeVec[0]; nodeVec[listLen - k - 1]->next = NULL; return nodeVec[listLen - k]; }
Both left-handed and right-handed can be implemented through the above method. The space complexity changesO(N), The time complexity is stillO(N).
The above is the result of my independent thinking. We can see that discuss has discussed the practice of setting two pointers. Based on this idea, I have implemented the following implementation:
Leetcode [linked list]: Rotate list