For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
Idea: Since k may be larger than the length of the list, we first need to know k%length by using a pointer to traverse the linked list and reset to the head if the pointer reaches null. Another way is to measure the length of the list first, then calculate k%length. The worst case time complexity is the same.
Then we split the list to two lists at the rotate position. The new head is the head of the second sublist. The end of the new list is the node right before the rotate position, set it to null.
Time: O(n) Space: O(1)
Code:
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head==null || head.next==null || n==0)
return head;
ListNode faster=head;
ListNode slower=head;
for(int i=0;i<n;i++)
{
if(faster==null)
faster=head;
faster=faster.next;
}
if(faster==null)
return head;
while(faster.next!=null)
{
faster=faster.next;
slower=slower.next;
}
ListNode newHead=slower.next;
faster.next=head;
slower.next=null;
return newHead;
}
}
No comments:
Post a Comment