LeetCode 61. Rotate List

原题链接在这里:https://leetcode.com/problems/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.

题解:

快慢指针, 先算长度len, runner停在tail node.

walker移动 len- k%len 步数后断开后面, runner.next指向head.

Note: corner case is k%len == 0. That is why we use dummy head.

Time Complexity: O(n). Space: O(1).

AC Java:

 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         
15         ListNode dummy = new ListNode(0);
16         dummy.next = head;
17         ListNode walker = dummy;
18         ListNode runner = dummy;
19         
20         int len = 0;
21         while(runner.next != null){
22             runner = runner.next;
23             len++;
24         }
25         
26         int jump = len-(k%len);
27         while(jump -- > 0){
28             walker = walker.next;
29         }
30         
31         runner.next = dummy.next;
32         dummy.next = walker.next;
33         walker.next = null;
34         
35         return dummy.next;
36     }
37 }

Rotate Array相似

posted @ 2015-10-14 11:10  Dylan_Java_NYC  阅读(421)  评论(0编辑  收藏  举报