您的位置:首页 > 编程语言 > Java开发

Rotate List

2014-06-10 14:43 183 查看

题目

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:

Given 
1->2->3->4->5->NULL
 and k = 
2
,

return 
4->5->1->2->3->NULL
.

方法

链表的旋转。
public ListNode rotateRight(ListNode head, int n) {
if (head == null) {
return null;
}
ListNode node = head;
int k = 0;
while (node != null) {
k++;
node = node.next;
}
int len = k;
n = n % len;
if (n == 0) {
return head;
}

ListNode start = new ListNode(0);
start.next = head;
ListNode pre = null;
ListNode end = null;
int i = 0;
end = start;
while (end.next != null) {

end = end.next;
if (pre != null) {
pre = pre.next;
}
i++;
if (i == n) {
pre = start;
}
}
if (i > n) {
end.next = start.next;
start.next = pre.next;
pre.next = null;
}
return start.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Java LinkedList