美文网首页
Leetcode 61 - Rotate List

Leetcode 61 - Rotate List

作者: BlueSkyBlue | 来源:发表于2018-07-31 21:55 被阅读15次

    题目:

    Given a linked list, rotate the list to the right by k places, where k is non-negative.
    Example 1:

    Input: 1->2->3->4->5->NULL, k = 2
    Output: 4->5->1->2->3->NULL
    Explanation:
    rotate 1 steps to the right: 5->1->2->3->4->NULL
    rotate 2 steps to the right: 4->5->1->2->3->NULL

    Example 2:

    Input: 0->1->2->NULL, k = 4
    Output: 2->0->1->NULL
    Explanation:
    rotate 1 steps to the right: 2->0->1->NULL
    rotate 2 steps to the right: 1->2->0->NULL
    rotate 3 steps to the right: 0->1->2->NULL
    rotate 4 steps to the right: 2->0->1->NULL


    思路:

    首先将链表变为循环链表。之后记录下链表的头结点head。一直往下走在链表长度减去head走过的步数为给定的数k的时候停下。此时head的下一个结点就是咱们要找的头结点。

    注意:
    如果给定的数k大于链表的长度length的时候需要用k%length


    代码:

    public ListNode rotateRight(ListNode head, int k) {
            if(head == null){
                return null;
            }
            if(head.next == null){
                return head;
            }
            ListNode previous = head;
            ListNode next = head.next;
            ListNode node = head;
            int length = 1;
            while(node.next != null){
                length++;
                node = node.next;
            }
            int newk = k%length;
            int count = 1;
            while(length - count != newk){
                previous = previous.next;
                count++;
            }
            node.next = head;
            head = previous.next;
            previous.next = null;
            return head;
    }
    

    相关文章

      网友评论

          本文标题:Leetcode 61 - Rotate List

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