1. 题目原址
https://leetcode.com/problems/rotate-list/
2. 题目描述
3. 题目大意
给定一个链表,和一个整数k,将第K个元素后面的元素翻转的链表前面
4. 解题思路
- 首先遍历一遍链表,得到链表的长度
- 然后计算需要反转的次数,并且找到需要第一次改变的位置
5. AC代码
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) return head;
int len=0;
ListNode p = head;
while (p!=null) {
len++;
p=p.next;
}
k %= len;
if (k==0) return head;// 计算需要旋转多少次
p=head;
int hops = len-k-1; // 找到需要改变位置的元素
while (hops > 0 && p!=null) {
p = p.next;
hops--;
}
ListNode newHead = p.next; // 需要反转的第一个元素的位置
ListNode q = newHead; // 这个q是要返回的链表的头
if (p!=null) p.next=null; // 将第一个反转的元素和前面元素断开
if (q != null) {
while (q.next != null) { // 从要反转的第一个元素开始一直遍历,遍历到链表的末尾
q=q.next;
}
q.next = head;
return newHead;
} else {
return head;
}
}
}
6. 相似题目
【1】189. Rotate Array https://leetcode.com/problems/rotate-array/
解法:https://blog.csdn.net/xiaojie_570/article/details/91416362