LeetCode 61 questions: rotation list (middle)

LeetCode 61 questions: rotation list (middle)

  • Title: Given a list, the list of rotation, each of the node list to the right by k positions, wherein k is non-negative.
  • Solution one: because declares first and second two nodes move (I do not know how to become a mobile node), put 0, 1, 2 nodes on top are special discussion.
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(k == 0 || head == null || head.next == null) return head;
        ListNode first = head.next;
        if(first.next == null){
            if(k%2 == 0){
                return head;
            }else{
                head.next = null;
                first.next = head;
                head = first;
                return head;
            }
        }
        int j = 2;
        while(first.next != null){
                first = first.next;
                j++;
        }
        k = k%j;
        for(int i=0;i<k;i++){
            first = head.next;
            ListNode second = first.next;
            while(second.next != null){
                first = second;
                second = first.next;
            }
            first.next = null;
            second.next = head;
            head = second; 

        }
        return head;
    }
}

Here Insert Picture Description

  • Solution two: Comparison of clever ideas, the list becomes a closed loop, and then determine where to open.
class Solution {
  public ListNode rotateRight(ListNode head, int k) {
    // base cases
    if (head == null) return null;
    if (head.next == null) return head;

    // close the linked list into the ring
    ListNode old_tail = head;
    int n;
    for(n = 1; old_tail.next != null; n++)
      old_tail = old_tail.next;
    old_tail.next = head;

    // find new tail : (n - k % n - 1)th node
    // and new head : (n - k % n)th node
    ListNode new_tail = head;
    for (int i = 0; i < n - k % n - 1; i++)
      new_tail = new_tail.next;
    ListNode new_head = new_tail.next;

    // break the ring
    new_tail.next = null;

    return new_head;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/rotate-list/solution/xuan-zhuan-lian-biao-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Here Insert Picture Description

Published 79 original articles · won praise 7 · views 1377

Guess you like

Origin blog.csdn.net/new_whiter/article/details/104248711