Rotate List

来源:互联网 发布:淘宝店一共有多少分 编辑:程序博客网 时间:2024/05/29 10:52

题目

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.

方法

链表的旋转。
    public ListNode rotateRight(ListNode head, int n) {        if (head == null) {            return null;        }        ListNode node = head;        int k = 0;        while (node != null) {        k++;        node = node.next;        }        int len = k;        n = n % len;        if (n == 0) {            return head;        }        ListNode start = new ListNode(0);        start.next = head;        ListNode pre = null;        ListNode end = null;        int i = 0;        end = start;        while (end.next != null) {            end = end.next;            if (pre != null) {                pre = pre.next;            }            i++;             if (i == n) {                pre = start;            }        }        if (i > n) {            end.next = start.next;            start.next = pre.next;            pre.next = null;        }        return start.next;    }


0 0