给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数
您在真实的面试中是否遇到过这个题?
Yes
样例
给出链表1->2->3->4->5->null和k=2
返回4->5->1->2->3->null
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: the List
* @param k: rotate to the right k places
* @return: the list after rotation
*/
public ListNode rotateRight(ListNode head, int k) {
// write your code here
if(head == null ) return null;
ListNode c = head;
int count = 0;
while(c!=null){
count++;
c = c.next;
}
ListNode x = head;
ListNode res = new ListNode(-1);
ListNode y = res;
ListNode front = new ListNode(-1);
ListNode z = front;
for(int i=0;i<count-k%count&&x!=null;i++){
z.next = x;
z = z.next;
x = x.next;
}
z.next = null;
while(x!=null){
y.next = x;
y = y.next;
x = x.next;
}
y.next = front.next;
return res.next;
}
}