题目

the leetcode link

解题思路

  1. 计算链表长度,同时初始化哈希索引
  2. 取余去重
  3. 形成环,链尾指向链头
  4. 定位到翻转后的尾结点
  5. 断链
  6. 返回新链头

    代码

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
/**
* 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) return head;

//哈希索引存储
Map<Integer,ListNode> map = new HashMap<>();
ListNode cur = head;
int len = 1;
//计算链表长度, 同时初始化哈希索引
while(cur.next != null){
map.put(len++, cur);
cur =cur.next;
}

//去重,转n*len+k次,等价于转k%len次,k%len=0等价与0次翻转
if((k=(k%len))==0) return head;

//形成环
cur.next = head;

//找到翻转后的尾结点
ListNode newTail = map.get(len-k);

//断开头尾
ListNode newHead = newTail.next;
newTail.next = null;

//返回头节点
return newHead;
}
}