61. 旋转链表

题目描述

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

输入输出

1
2
3
4
5
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]

输入:head = [0,1,2], k = 4
输出:[2,0,1]

基本思路

  1. 先求出链表长度length和标记尾节点指针tail
  2. new一个新指针p 往后移动length - k%length - 1步到达新链表头结点
  3. p -> null head = p.next tail -> head

java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || k == 0) return head;
int length = 0;
ListNode tail = null;
for(ListNode p = head; p != null; p = p.next) {
tail = p;
length++;
}
k = k%length;
int move = length - k - 1;//move = 3
ListNode p = head;
for(int i = 0; i < move; i++){
p = p.next;
}
tail.next = head;
head = p.next;
p.next = null;
return head;

}
}