题意描述:
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例:
- 示例一:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
- 示例二:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
解题思路:
Alice: 这道题有点奇怪哦 ?
Bob: 哪里奇怪了 ?
Alice: 明明是很简单的题目,修改一下链表就行了,怎么就放到中级难度的题目里面了,不是很理解。
Bob: 修改一下链表就行了 ?
Alice: 不是吗,你先把链表的尾和头连起来,然后在找到合适的位置断开,然后返回新链表的头不就好了。
Bob: 找到合适的位置 ? 不就是从 最初的头结点开始数,第 k 个节点嘛。
Alice: 那可不一定,万一 k 是一个比较大的数呢 ?
Bob: 哦哦,你是说 k 大于 链表中节点总数的情况是吧,那还要取一下余数。
Alice: 😎😎
代码:
Python 方法一: 就按照题目的逻辑来呗。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if head == None:
return head
cnt = 0
node = head
while node.next != None:
cnt += 1
node = node.next
tail = node
cnt += 1
#print(cnt)
if k == 0 or k % cnt == 0:
# 无需移动
return head
k = cnt - (k % cnt)
anotherCnt = 1
node = head
while anotherCnt != k:
node = node.next
anotherCnt += 1
#print("tail ", tail.val)
#print("node ", node.val)
tail.next = head
ret = node.next
node.next = None
return ret
Java 方法一:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null){
// 边界值输入
return head;
}else{
int cnt = 0;
ListNode node = head;
while(node.next != null){
cnt += 1;
node = node.next;
}
ListNode tail = node;
cnt += 1;
// 记录链表的尾结点 和 节点总数
if(k == 0 || k % cnt == 0){
return head;
}
// 不需要旋转的情况
k = cnt - (k % cnt);
int anotherCnt = 1;
node = head;
while(anotherCnt < k){
// 找到需要 旋转的 节点
node = node.next;
anotherCnt += 1;
}
// 转就完了
tail.next = head;
// 转之前要保留最后的返回值
ListNode ret = node.next;
node.next = null;
return ret;
}
}
}
易错点:
- 注意边界值输入。
- 一些测试样例:
[1,2,3,4,5]
2
[1,2,3,4,5]
3
[0,1,2]
4
[0,1,2]
9
[0,1,2]
0
[1]
122
[1,2]
1
[]
99
- 答案
[4,5,1,2,3]
[3,4,5,1,2]
[2,0,1]
[0,1,2]
[0,1,2]
[1]
[2,1]
[]
总结:
- 鼠年大吉,祝您平安。😄😄