-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path0061.旋转链表.java
81 lines (77 loc) · 1.57 KB
/
0061.旋转链表.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* @lc app=leetcode.cn id=61 lang=java
*
* [61] 旋转链表
*
* https://leetcode.cn/problems/rotate-list/description/
*
* algorithms
* Medium (41.59%)
* Likes: 845
* Dislikes: 0
* Total Accepted: 285.8K
* Total Submissions: 687.3K
* Testcase Example: '[1,2,3,4,5]\n2'
*
* 给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
*
*
*
* 示例 1:
*
*
* 输入:head = [1,2,3,4,5], k = 2
* 输出:[4,5,1,2,3]
*
*
* 示例 2:
*
*
* 输入:head = [0,1,2], k = 4
* 输出:[2,0,1]
*
*
*
*
* 提示:
*
*
* 链表中节点的数目在范围 [0, 500] 内
* -100 <= Node.val <= 100
* 0 <= k <= 2 * 10^9
*
*
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k == 0)
return head;
ListNode current = head;
int length = 1;
while (current.next != null) {
current = current.next;
length++;
}
int index = length - k % length;
if (index == length)
return head;
current.next = head;
while (index-- > 0)
current = current.next;
head = current.next;
current.next = null;
return head;
}
}
// @lc code=end