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

Rotate List

时间:2016-08-16 00:02:55      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode rotateRight(ListNode head, int k) {
11         if (head == null || head.next == null) {
12             return head;
13         }
14         ListNode dummy = new ListNode(0);
15         dummy.next = head;
16         ListNode node = dummy;
17         int len = 0;
18         ListNode tail;
19         while (node.next != null) {
20             len++;
21             node = node.next;
22         }
23         //System.out.println(len);
24         tail = node;
25         k = k % len;
26         if (k == 0) {
27             return dummy.next;
28         }
29         node = dummy;
30         for (int i = 0; i < len - k; i++) {
31             node = node.next;
32         }
33         tail.next = dummy.next;
34         dummy.next = node.next;
35         node.next = null;
36         return dummy.next;
37     }
38 }

 

Rotate List

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5774672.html

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