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;
            }
        }
    
    }
  • 相关阅读:
    3年A班,从现在起大家都是人质-观后感
    深入浅出的Object.defineProperty()
    在Vue中使用插槽(solt)
    非父子组件间的传值
    给组件绑定原生事件
    组件参数校验与非props特性
    Vue父子组件的数据传递
    Vue组件使用中的细节点
    vue中set基本用法
    vue中的列表渲染
  • 原文地址:https://www.cnblogs.com/null00/p/5080438.html
Copyright © 2011-2022 走看看