您的位置:首页 > 其它

[leetcode] Rotate List

2014-06-26 15:17 309 查看
Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.

https://oj.leetcode.com/problems/rotate-list/

思路1:先遍历一遍求长度,然后从头再开始走k%len步,设置新的头尾节点,连接原来的头尾节点。

思路2:遍历求长度,将首尾连接,继续走到新的头尾,断开。

思路1代码:

public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if (head == null)
return null;
int len = 0;
ListNode p = head;
while (p != null) {
len++;
p = p.next;
}

p = head;
int i;
n = n % len;
if (n == 0)
return head;
for (i = 0; i < len - n - 1; i++)
p = p.next;
ListNode newTail = p;
ListNode newHead = p.next;

while (p.next != null)
p = p.next;
p.next = head;
newTail.next = null;
return newHead;

}

public static void main(String[] args) {
ListNode head = ListUtils.makeList(1, 2, 3, 4, 5);
ListUtils.printList(head);
head = new Solution().rotateRight(head, 2);
ListUtils.printList(head);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: