p61

LeetCode p61 Rotate List 题解

1.题目:

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.

题意:

输入一个链表转置它末尾的K个数。

2.解题思路:

见代码,输入的K可能会超过链表长度。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0)
return head;
int count = 0;
ListNode fast = head;
ListNode slow = head;
while (fast != null) {
fast = fast.next;
count++;
}
count = k % count;
if (count == 0)
return head;
fast = head;
while (count > 0 && fast != null) {
fast = fast.next;
count--;
}
if (fast == null)
return head;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
ListNode ans = slow.next;
fast.next = head;
slow.next = null;
return ans;
}
}

4.一些总结: