Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
1->2->3->4->5->NULL and k = 2,return
4->5->1->2->3->NULL.Analysis:
1. The list could be empty, i.e. head == null.
2. Build a circle based on the original list andfind the number of nodes of such list. These two things can be done simultaneously by traversing the list one time.
3. Find the index of the last node of the newly generated list, which should be num_nodes - (n % num_nodes).
4. The head of the new list should be the next node of the last node, since the whole list is a circle now.
5. Break the circle by appropriately handling the first and last nodes of the newly created list.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public int getLengthAndBuildCycle(ListNode head, ListNode cur, int len) {
while(cur.next != null) {
cur = cur.next;
len++;
}
cur.next = head; // build a circle, important logic!!!
return len;
}
public ListNode rotateRight(ListNode head, int n) {
if(n==0 || head==null) return head;
ListNode cur=head, res=head;
int len = getLengthAndBuildCycle(head, cur, 1); // get the length of this list
for(int i=1; i<len-n%len; i++) { // res points the last node after this loop
res = res.next;
}
cur = res; // cur points to the last node of the newly generated list
res = res.next; // res points to the first node of the newly generated list
cur.next = null;
return res;
}
}

301

被折叠的 条评论
为什么被折叠?



