美文网首页
LeetCode每日一题:rotate list

LeetCode每日一题:rotate list

作者: yoshino | 来源:发表于2017-06-05 10:55 被阅读14次

问题描述

Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.

问题分析

这题很麻烦,n可能很大,需要取余才能确定分界点,链表操作没有什么难点。

代码实现

public ListNode rotateRight(ListNode head, int n) {
        if (head == null) return null;
        ListNode tmp = head;
        int len = 0;
        while (tmp != null) {
            len++;
            tmp = tmp.next;
        }
        n = n % len;
        if (n == 0) return head;
        ListNode cur, fast, slow;
        cur = fast = slow = head;
        for (int i = 0; i < n; i++) {
            if (fast != null) fast = fast.next;
            else return null;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        ListNode newHead = slow.next;
        slow.next = null;
        fast.next = cur;
        return newHead;
    }

相关文章

网友评论

      本文标题:LeetCode每日一题:rotate list

      本文链接:https://www.haomeiwen.com/subject/purifxtx.html