The idea is to locate the rotate start node first, by set two pointers with distance k, and loop to the end of the list at the same time. The 1st pointer next is the new head.
Be careful one case that the rotate start node has a very large chance to be the same as tail node. let's say 1->2->null and k = 3 or 1->null and k = 1.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head == null || n == 0){
return head;
}
ListNode cur = head;
ListNode tar = head;
int index = 0;
while(index++ < n){
tar = tar.next;
if(tar == null){
tar = head; //n can be more than actual size.
}
}
while(tar.next != null){
cur = cur.next;
tar = tar.next;
}
if(cur.next == null)
return head;
ListNode newHead = cur.next;
cur.next = null;
tar.next = head;
return newHead;
// ListNode newHead = new ListNode(Integer.MAX_VALUE);
// newHead.next = head;
// ListNode kNode = head;
// for(int i = 0; i < n; i++){
// if(kNode.next != null){ //kNode != null
// kNode = kNode.next;
// }else{
// kNode = newHead.next;
// }
// }
// ListNode newTail = newHead.next;
// while(kNode.next != null){
// newTail = newTail.next;
// kNode = kNode.next;
// }
// kNode.next = newHead.next;
// newHead.next = newTail.next;
// newTail.next = null;
// return newHead.next;
}
}
没有评论:
发表评论