zoukankan      html  css  js  c++  java
  • [leetcode]Rotate List

    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.

    算法思路:

    注意处理边界情况,k > length,需要取余的,坑爹。k == 0 || length时,不作处理

     1 public class Solution {
     2     public ListNode rotateRight(ListNode head, int n) {
     3         ListNode hhead = new ListNode(0);
     4         hhead.next = head;
     5         ListNode tail = hhead;
     6         int length = 0;
     7         while(tail.next != null){
     8             length++;
     9             tail = tail.next;
    10         }
    11         if(length == 0 || n == 0) return head;
    12         if(n >= length) n %= length;
    13         ListNode pre = hhead;
    14         for(int i = 0; i < length - n; pre = pre.next,i++);
    15         tail.next = hhead.next;
    16         hhead.next = pre.next;
    17         pre.next = null;
    18         return hhead.next;
    19     }
    20 }
  • 相关阅读:
    uboot misc
    Android Q dynamic partition
    Android Verified Boot 2.0简要
    dts参考资料
    SWT问题分析总结
    lzma文件及命令简介
    C++之继承
    C++之常指针
    C++之对象成员指针
    C++之对象指针
  • 原文地址:https://www.cnblogs.com/huntfor/p/3855315.html
Copyright © 2011-2022 走看看