LeetCode 61. 旋转链表C#
原题链接
中等
作者:
hpstory
,
2022-08-05 00:19:49
,
所有人可见
,
阅读 114
C# 代码
public class Solution {
public ListNode RotateRight(ListNode head, int k) {
if(head == null) return head;
ListNode dummy = new ListNode(0, head);
// 求链表长度
int length = 0;
ListNode current = dummy.next;
while (current != null){
length++;
current = current.next;
}
k = k % length;
if (k == 0) return head;
ListNode fast = dummy;
ListNode slow = dummy;
while (k-- >0){
fast = fast.next;
}
// 快慢指针求出断开位置
while (fast.next != null){
fast = fast.next;
slow = slow.next;
}
// 链表结尾连接到头节点
fast.next = head;
// 新的头节点是slow节点的下一个节点
ListNode newHead = slow.next;
// 一定要断开slow节点, 否则会报OOM
slow.next = null;
return newHead;
}
}