码迷,mamicode.com
首页 > 其他好文 > 详细

Rotate List

时间:2016-07-03 07:00:45      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

Given a list, rotate the list to the right by k places, where k is non-negative.

Example

Given 1->2->3->4->5 and k = 2, return 4->5->1->2->3.

分析:

先得到list size, 然后 k = k % size. 找到新head,然后把tail链接到head.

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param head: the List
15      * @param k: rotate to the right k places
16      * @return: the list after rotation
17      */
18     public ListNode rotateRight(ListNode head, int k) {
19         if (head == null || head.next == null) return head; 
20         // write your code here
21         int size = size(head);
22         k = k % size;
23         
24         if (k == 0) return head;
25         ListNode pointer = head;
26         for (int i = 1; i <= size - k - 1; i++) {
27             pointer = pointer.next;
28         }
29         
30         ListNode newHead = pointer.next;
31         pointer.next = null;
32         
33         // link the tail to the head
34         ListNode current = newHead;
35         while (current.next != null) {
36             current = current.next;
37         }
38         current.next = head;
39         return newHead;
40     }
41     
42     public int size(ListNode head) {
43         int count = 0;
44         while (head != null) {
45             count++;
46             head = head.next;
47         }
48         return count;
49     }
50 }

转载请注明出处:cnblogs.com/beiyeqingteng/

Rotate List

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5636474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!