您的位置:首页 > 其它

leetcode -- Rotate List

2013-08-12 23:38 176 查看
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
.

[解题思路]

初始的想法是类似于求倒数第k个数,结果发现k可能会比len大,到网上搜索了下:

从head节点开始跑,一直跑到尾节点,得到len,将尾节点的next指针指向head,接着跑(len -n) % len步,断开

这里需注意(len -n) % len可能为负数,需+len

/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null || n == 0){
return head;
}
int len = 1;
ListNode p = head;
while(p.next != null){
len ++;
p = p.next;
}
p.next = head;
/*
int count = (len - n - 1) % len;
while(count < 0){
count += len;
count %= len;
}
p = head;
*/
int count = (len - n) % len;
while(count < 0){
count += len;
count %= len;
}
int step = 0;
while(step < count){
p = p.next;
step ++;
}
head = p.next;
p.next = null;
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: