61. Rotate List
Description
描述:https://leetcode.com/problems/rotate-list/description/
题意:对于给定链表,向右旋转k个位置。
Solution: (Java)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (k == 0 || head == null)
return head;
ListNode tmp = head, tmp2 = head, ret = null, end = null;
int len = 0;
while (tmp != null) { //遍历一遍统计链表长度,同时确定链表的结尾end
len++;
end = tmp;
tmp = tmp.next;
}
k = k % len; //取余得出实际需要旋转的数
if (k == 0)
return head;
k = len - k; //实际遍历的终止位置
int count = 0;
while (tmp2 != null) {
count++;
if (count == k) {
ret = tmp2.next;
tmp2.next = null;
end.next = head;
break;
}
tmp2 = tmp2.next;
}
return ret;
}
}
思路
- 本题 runtime 0ms,beat 100%;
- 先遍历一遍统计链表长度,然后第二遍遍历到需要旋转的点,改变链表的结尾和开头即可。