61. Rotate List

作者: 番茄晓蛋 | 来源:发表于2017-06-18 06:58 被阅读3次

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.

** 解题思路 **
用快慢指针,分三步来做。第一步用fast 指针算出链表长度;第二步用slow 指针定位要旋转的位置;第三步作旋转。
Since n may be a large number compared to the length of list. So we need to know the length of linked list.After that, move the list after the (l-k%l )th node to the front to finish the rotation.

Ex: {1,2,3} k=2 Move the list after the 1st node to the front

Ex: {1,2,3} k=5, In this case Move the list after (3-5%3=1)st node to the front.

So the code has three parts.

(1) Get the length

(2) Move to the (l-k%l)th node

(3)Do the rotation

 public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null) return head;
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode fast = dummy, slow = dummy;
        int size = 0;
        // Get the total length
        while (fast.next != null) {
            size++;
            fast = fast.next;
        }
        // Get the size - k % size th node
        for (int j = size - k % size; j > 0; j--) {
           slow = slow.next;   
        }
        // do the rotation
        fast.next = dummy.next;
        dummy.next = slow.next;
        slow.next = null;
        
        return dummy.next;
    }

相关文章

  • 61. Rotate List

    题目61. Rotate List Given a list, rotate the list to the ri...

  • 61. Rotate List

    61. Rotate List

  • LeetCode 61-65

    61. Rotate List[https://leetcode-cn.com/problems/rotate-l...

  • 【D33】旋转链表 (LC61)

    61. 旋转链表[https://leetcode-cn.com/problems/rotate-list/] 给...

  • 61. Rotate List

    这一题边界需要考虑一些边界条件:1,k=02, 链表为空或者链表中只有一个元素 旋转的step为0代码如下:

  • 61. Rotate List

    Given a list, rotate the list to the right by k places, w...

  • 61. Rotate List

    题目 Given a list, rotate the list to the right by k places...

  • 61. Rotate List

    题目描述:给一个链表和非负整数k,将其在下标k处翻转。如: Given 1->2->3->4->5->NULL a...

  • 61. Rotate List

    Given a list, rotate the list to the right by k places, w...

  • 61. Rotate List

    Given a list, rotate the list to the right by k places, w...

网友评论

    本文标题: 61. Rotate List

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