题目:
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
代码:
public class Test17 {
public ListNode rotateRight(ListNode head, int k) {
if (head==null) {
return head;
}
ListNode temp = head;
int num = 1;
while (temp.next != null) {
temp = temp.next;
num++;
}
k=k%num;
if (k==0) {
return head;
}
k=num-k-1;
temp.next=head;
while (k > 0) {
head = head.next;
k--;
}
ListNode result = head.next;
head.next=null;
return result;
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}