标签:
题目链接:https://leetcode.com/problems/rotate-list/
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.
Subscribe to see which companies asked this question
题目不难,但是边界条件十分让人抓狂。重点考虑以下三个边界case:
public class RotateList {
public static void main(String[] args) {
ListNode h = new ListNode(1);
h.next = null;
rotateRight(h, 1);
}
public static ListNode rotateRight(ListNode head, int k) {
if (head == null) return null;
ListNode h = new ListNode(0);
h.next = head;
ListNode p1 = h, p2 = h, p = h;
int len = 0;
while (p.next != null) {
p = p.next;
len++;
}
k %= len;
if (k == 0) return head;
for (int i = 0; i < k; i++) p2 = p2.next;
while (p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}
h.next = p1.next;
p2.next = head;
p1.next = null;
return h.next;
}
}LeetCode OJ 61. Rotate List 考虑边界条件
标签:
原文地址:http://blog.csdn.net/bruce128/article/details/51684656