题意:
按要求右移一个链表。
思路:
一开始想的是按照右移字符串的思路,倒置三次链表/http://blog.csdn.net/zzran/article/details/8456721
后来发觉,其实只要找到右移后新的表头,然后把链表重新连接一下就行。
java代码:
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null||head.next==null){
return head;
}
ListNode root = head;
int len = 1;
while(root.next!=null){
len++;
root = root.next;
}
k = k%len;
if(k==0){
return head;
}
ListNode fast = head;
ListNode slow = head;
while(k>0){
fast = fast.next;
k--;
}
while(fast.next!=null){
fast = fast.next;
slow = slow.next;
}
root = slow.next;
slow.next = null;
fast.next = head;
return root;
}
}