題目描述
鏈接:https://leetcode-cn.com/problems/rotate-list/
給你一個(gè)鏈表的頭節(jié)點(diǎn) head ,旋轉(zhuǎn)鏈表,將鏈表每個(gè)節(jié)點(diǎn)向右移動(dòng) k 個(gè)位置。
示例
輸入:head = [1,2,3,4,5], k = 2
輸出:[4,5,1,2,3]
代碼
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k <= 0) {
return head;
}
int length = 1; // 鏈表長(zhǎng)度
ListNode tempHead = head;
ListNode lastNode = null; // 鏈表最后一個(gè)節(jié)點(diǎn)
// 計(jì)算鏈表長(zhǎng)度
while (tempHead.next != null) {
length ++;
tempHead = tempHead.next;
}
lastNode = tempHead;
// 如果k大于鏈表長(zhǎng)度,則取余數(shù)
if (k >= length) {
k = k % length;
}
// 如果k = 0,表示不用旋轉(zhuǎn),則直接返回head
if (k == 0) {
return head;
}
// 找到旋轉(zhuǎn)后鏈表的頭部位置
tempHead = head;
for (int i = 0; i < length - k - 1; i++) {
tempHead = tempHead.next;
}
ListNode newHead = tempHead.next;
tempHead.next = null; // 斷開指向頭部的指針
lastNode.next = head; // 鏈表最后一個(gè)元素執(zhí)行原始的頭節(jié)點(diǎn)
return newHead;
}