zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    HDOJ骨头的诱惑
    DP Big Event in HDU
    hoj1078
    poj2728
    hoj1195
    poj2739
    poj2726
    海量并发也没那么可怕,运维准点下班全靠它!
    云上安全工作乱如麻,等保2.0来一下
    实践案例丨教你一键构建部署发布前端和Node.js服务
  • 原文地址:https://www.cnblogs.com/anne-vista/p/5551786.html
Copyright © 2011-2022 走看看