zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    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.

    思路:

    此题和Remove Nth Node from End of List类似,但首先得统计总的个数

    package list;
    
    public class RotateList {
    
        public ListNode rotateRight(ListNode head, int k) {
            if (k == 0 || head == null) return head;
            
            ListNode x = head;
            int count = 0;
            while (x != null) {
                ++count;
                x = x.next;
            }
            
            int n = k;
            if (k >= count) {
                if (k % count == 0)
                    return head;
                else
                    n = k % count;
            }
                
            ListNode p = head;
            ListNode q = head;
            while (p != null && n > 0) {
                p = p.next;
                --n;
            }
            
            while (p.next != null && q.next != null) {
                p = p.next;
                q = q.next;
            }
            
            ListNode newhead = q.next;
            p.next = head;
            q.next = null;
            return newhead;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            RotateList r = new RotateList();
            ListNode a1 = new ListNode(1);
            ListNode a2 = new ListNode(2);
            ListNode a3 = new ListNode(3);
            ListNode a4 = new ListNode(4);
            ListNode a5 = new ListNode(5);
            a1.next = a2;
            a2.next = a3;
            a3.next = a4;
            a4.next = a5;
            a5.next = null;
            ListNode head = r.rotateRight(a1, 2);
            while (head != null) {
                System.out.println(head.val);
                head = head.next;
            }
        }
    
    }
  • 相关阅读:
    Leetcode:50. Pow(x, n)
    loj 2759「JOI 2014 Final」飞天鼠
    bzoj 3569 DZY Loves Chinese II
    CF407D Largest Submatrix 3
    bzoj 3837 pa2013 Filary
    bzoj 4722 由乃
    CF1105E Helping Hiasat
    loj 6043「雅礼集训 2017 Day7」蛐蛐国的修墙方案
    luogu P2605 [ZJOI2010]基站选址
    luogu P3226 [HNOI2012]集合选数
  • 原文地址:https://www.cnblogs.com/null00/p/5080438.html
Copyright © 2011-2022 走看看