首页 > 其他 > 详细

Rotate List

时间:2016-08-16 00:00:35      阅读:124      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!