zoukankan      html  css  js  c++  java
  • LeetCode 61 Rotate List

    这道题目恶心就在于,你要判断k跟list长度之间的大小关系。

    所以要先求长度。

     1 public class Solution {
     2   public ListNode rotateKplace(ListNode head, int k) {
     3     // Write your solution here
     4     if (head == null || head.next == null) {
     5       return head;
     6     }
     7     k = k % getNum(head);
     8     if (k == 0) {
     9      return head; 
    10     }
    11     
    12     ListNode fast = head;
    13     ListNode slow = head;
    14     for (int i = 0; i < k - 1; i++) {
    15       fast = fast.next;
    16     }
    17     ListNode prev = null;
    18     while (fast.next != null) {
    19       prev = slow;
    20       slow = slow.next;
    21       fast = fast.next;
    22     }
    23     prev.next = null;
    24     fast.next = head;
    25     return slow;
    26   }
    27   
    28   private int getNum(ListNode head) {
    29     int count = 0;
    30     while (head != null) {
    31       count++;
    32       head = head.next; 
    33     }
    34     return count;
    35   }
    36 }
  • 相关阅读:
    zoj1589Professor John
    zoj1082Stockbroker Grapevine
    zoj1311Network
    zoj1060Sorting It All Out
    zoj1119SPF
    zju1085Alien Security
    zoj 2474Benny's Compiler
    zoj1068P,MTHBGWB
    what's next?
    ski for the first time~
  • 原文地址:https://www.cnblogs.com/mayinmiao/p/8492352.html
Copyright © 2011-2022 走看看