Lexi's Leetcode solutions

[leetcode] Rotate List | 把后k个rotate到list前面去,k可以超过list本身长度

Posted on: August 14, 2013

看别人思路:这个既然要rotate,不如先连起来loop,这样怎么也不怕null pointer exception了。然后再找到该断开的地方断开。

public ListNode rotateRight(ListNode head, int n) {

    if (head == null || n == 0)
        return head;
    ListNode p = head;
    int len = 1;//since p is already point to head
    while (p.next != null) {
        p = p.next;
    p.next = head; //form a loop
    n = n % len;
    for (int i = 0; i < len - n; i++) { //len-n一画就出来了
        p = p.next;
    } //now p points to the prev of the new head
    head = p.next;
    p.next = null;
    return head;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: