题目
给你一个链表的头节点 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]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
使用位置标记
/**
* 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) return head;
int len = 0;
ListNode p = head;
while(p != null){
len++;
if(p.next != null) p = p.next;
else break;
}
k = (len - k % len) % len;
if(k == 0) return head;
ListNode q = head;
while(--k > 0){
q = q.next;
}
ListNode r = q.next;
q.next = null;
q = r;
p.next = head;
return q;
}
}
环的思路
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || head.next == null) return head;
ListNode p = head;
int count = 1;
while(p.next != null){
p = p.next;
count++;
}
p.next = head;
k = count - k % count;
while(k-- > 0){
p = p.next;
}
head = p.next;
p.next = null;
return head;
}
}