[LeetCode]--61. 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.

我是利用双指针吧,就可以在一次遍历的情况下找到要断开的位置即倒数第几个位置,然后插到头上即可。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null || head.next == null)
            return head;
        ListNode p, q;
        p = q = head;
        int len = 1;
        while (p.next != null) {
            p = p.next;
            len++;
        }
        k = k % len;
        if (k == 0)
            return head;
        p = head;
        for (int i = 0; i < k; i++) {
            p = p.next;
        }
        while (p.next != null) {
            q = q.next;
            p = p.next;
        }
        p.next = head;
        p = q.next;
        q.next = null;
        head = p;
        return head;
    }
}

你可能感兴趣的:(LeetCode,算法,旋转链表算法)