LeetCode61. 旋转链表🌟🌟🌟中等
课后作业
问题描述
原文链接:61. 旋转链表
给你一个链表的头节点 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 <= 1000 <= k <= 2 * 109
代码实现
Java
/**
* 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 n = 1;
ListNode temp = head;
while(temp.next != null){
n++;
temp = temp.next;
}
k = k % n;
if(k - n == 0){
return head;
}
temp.next = head;
//定位到第 n - k 个节点,然后拆开。
for(int i = 1; i < n - k; i++){
head = head.next;
}
ListNode newHead = head.next;
// 拆开环
head.next = null;
return newHead;
}
}
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head == None or head.next == None:
return head
n = 1
temp = head
while temp.next != None:
n += 1
temp = temp.next
k = k % n
if k - n == 0:
return head
temp.next = head
#定位到第 n - k 个节点,然后拆开。
for i in range(1, n - k):
head = head.next
newHead = head.next
# 拆开环
head.next = None
return newHead
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(head == nullptr || head->next == nullptr){
return head;
}
int n = 1;
ListNode* temp = head;
while(temp->next != nullptr){
n++;
temp = temp->next;
}
k = k % n;
if(k - n == 0){
return head;
}
temp->next = head;
//定位到第 n - k 个节点,然后拆开。
for(int i = 1; i < n - k; i++){
head = head->next;
}
ListNode* newHead = head->next;
// 拆开环
head->next = nullptr;
return newHead;
}
};
Go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func rotateRight(head *ListNode, k int) *ListNode {
if head == nil || head.Next == nil {
return head
}
//计算链表长度
n := 1
temp := head
for temp.Next != nil {
n++
temp = temp.Next
}
//调整K
k = k % n
if k - n == 0 {
return head
}
//形成环形链表
temp.Next = head
//定位到第 n - k 个节点,然后拆开。
for i := 1; i < n-k; i++ {
head = head.Next
}
newHead := head.Next
// 拆开环
head.Next = nil
return newHead
}
评论(9)
时间复杂度:O(N),最坏情况下,遍历两次链表
时间复杂度:O(1)
这里我用的是拆链
就是将前驱和目标那个线断掉,变成两个链表再组合下,返回目标节点,就是整合链表的头,
重写
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
//先剪枝,旋不旋转一个样儿
if(headnullptr||head->nextnullptr||k0){
return head;
}
};
打卡
https://leetcode.cn/problems/rotate-list/solutions/2626182/61-xuan-zhuan-lian-biao-by-yukislab-2t3g
闭合为环
打卡