这道题目恶心就在于,你要判断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 }

 

posted on 2018-03-02 11:34  mayinmiao  阅读(85)  评论(0编辑  收藏  举报