[leetcode] 61. 旋转链表

61. 旋转链表

先求出链表的长度,并把链表首尾相连

然后题目中要求向右转,我们让k`=len-k 改成向左转

然后遍历到第(k-1)个节点,与下一个节点断开即可 (k-1).next即为新的head

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        ListNode p = head;
        ListNode last = new ListNode(-1);
        if (p == null) {
            return null;
        }
        int len = 0;
        while (p != null) {
            last = p;
            p = p.next;
            len++;
        }
        last.next = head;
        k %= len;
        k = len - k;
        p = head;
        while (k > 1) {
            p = p.next;
            k--;
        }

        last = p.next;
        p.next = null;
        return last;

    }
}

posted @ 2018-07-24 21:42  ACBingo  阅读(158)  评论(0编辑  收藏  举报