将链表向右移动n个单位。 由于链表向右移动我们每次都要确定新的链表尾部以便下次移动,但是链表尾部是上个尾部的前一节点,在单向的链表中我们只有遍历链表才能获得。这样直接按照题意来做的话循环内每次还要遍历一遍链表,代价是O(n*n),不太合理。
实际上,我们发现如果链表长l,那么向右移动l次链表无变化。如果n<l,那么向右移动n次相当于向左移动l-n次。 而向左移动我们每次需要确定新的头指针,这个指针可以直接利用上个头指针的next来直接获取,比较方便。 因而我们可以吧这道题变成向左移动来做。
/**
* 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) {
ListNode st=head;
int len=1;
if( head==null || n==0 || head.next==null)
{
return head;
}
while( st.next!=null )
{
len++;
st=st.next;
}
int l=len;
while( l<n )
{
l+=len;
}
ListNode tail=st;
st = head;
for( int i=0;i<l-n;i++ )
{
ListNode tmp=st.next;
st.next=null;
tail.next=st;
tail=st;
st=tmp;
}
return st;
}
}