61. Rotate List

61. 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.

 

一开始读错题了, 想难了,其实很简单。

1 假设list长度为len  ,快指针先走len-k步,

2.改变指向。

 1 class Solution {
 2     public ListNode rotateRight(ListNode head, int k) {
 3         if(head==null) return head;
 4         int len = 0;
 5         for(ListNode p = head;p!=null;p=p.next)
 6             len = len + 1;
 7         k = k%len;
 8         if(k==0) return head;
 9         ListNode faster=head;
10         ListNode slower;
11         //find the node to rotate
12         for(int i = len - k;i > 1;i--)
13             faster = faster.next;
14         slower = faster;
15        // slower.next = null;//放在这里错误!!!
16         faster = faster.next;
17         slower.next = null;//放在这里正确!!!
18         ListNode newhead = faster;
19         while(faster.next != null)
20             faster = faster.next;
21         faster.next = head;
22         return newhead;
23         
24     }
25     
26 }

ps:完全自己想出来的。

posted @ 2017-10-02 22:33  乐乐章  阅读(132)  评论(0编辑  收藏  举报