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]
|
基本思路
- 先求出链表长度
length
和标记尾节点指针tail
- new一个新指针
p
往后移动length - k%length - 1
步到达新链表头结点
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; ListNode p = head; for(int i = 0; i < move; i++){ p = p.next; } tail.next = head; head = p.next; p.next = null; return head;
} }
|