给你一个链表的头节点 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]
提示:
- 链表中节点的数目在范围
[0, 500]
内 -100 <= Node.val <= 100
0 <= k <= 2 * 109
将链表右半部分的 k 的节点拼接到 head 即可。
注:k 对链表长度 n 取余,即 k %= n
。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if k == 0 or head is None or head.next is None:
return head
n, cur = 0, head
while cur:
n, cur = n + 1, cur.next
k %= n
if k == 0:
return head
p = q = head
for i in range(k):
q = q.next
while q.next:
p, q = p.next, q.next
start = p.next
p.next = None
q.next = head
return start
/**
* 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 (k == 0 || head == null || head.next == null) {
return head;
}
ListNode cur = head;
int n = 0;
while (cur != null) {
cur = cur.next;
++n;
}
k %= n;
if (k == 0) {
return head;
}
ListNode p = head, q = head;
while (k-- > 0) {
q = q.next;
}
while (q.next != null) {
p = p.next;
q = q.next;
}
ListNode start = p.next;
p.next = null;
q.next = head;
return start;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode RotateRight(ListNode head, int k) {
if (k == 0 || head == null || head.next == null)
{
return head;
}
ListNode cur = head;
var n = 0;
while (cur != null)
{
cur = cur.next;
++n;
}
k %= n;
if (k == 0)
{
return head;
}
ListNode p = head, q = head;
while (k-- > 0)
{
q = q.next;
}
while (q.next != null)
{
p = p.next;
q = q.next;
}
ListNode start = p.next;
p.next = null;
q.next = head;
return start;
}
}