• Leetcode 61. Rotate List


    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.


    Analysis:

    1. compute the length of list m
    2. partition list into two small list, 注意正好移到list尾端,下一个是NULL!!
        before list is list1, after list is list2, set last node in list1 list1.next = null
    3. concatenate the tail of two list to the head of one list


    Java code

    20160601

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            //1. compute the length of list m
            //2. partition list into two small list,
            //     before list is list1, after list is list2, set last node in list1 list1.next = null
            //3. concatenate the tail of two list to the head of one list
            
             //base case
            if(head == null || head.next == null || k == 0) {
                return head;
            }
            int m = getLength(head);
            int moveStep = m - k % m - 1;
            ListNode cur = head;
            ListNode one = head;
            ListNode two = null;
            
            while(moveStep > 0) {
                cur = cur.next;
                moveStep--;
            }
            if(cur.next == null) {  //move to the end of the linked list, no rotate
                return head;
            }
            two = cur.next;
            cur.next = null;
            ListNode twohead = two;
            while(two.next != null) {
                two = two.next;
            }
            two.next = one;
            return twohead;
        }
        
        private int getLength(ListNode head) {
            int len = 0;
            while(head != null) {
                head = head.next;
                len++;
            }
            return len;
        }
    }
  • 相关阅读:
    NLP(二十九)一步一步,理解Self-Attention
    树莓派4B踩坑指南
    树莓派4B踩坑指南
    树莓派4B踩坑指南
    【2020.4.17】发现GitHub图片又裂了
    右键管理-干掉多余又删不掉的access
    Python format参数中的列表和元组可以使用“*”
    树莓派4B踩坑指南
    树莓派4B踩坑指南
    树莓派4B踩坑指南
  • 原文地址:https://www.cnblogs.com/anne-vista/p/5551786.html
Copyright © 2020-2023  润新知