61. Rotate List

在这里插入图片描述
在这里插入图片描述
主体思想都是构建环形链表

解法1:

# 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:
        res=ListNode(-1)
        res.next=head
        count=0
        while res.next:#计算链表长度
            count=count+1
            res=res.next
        if count==0:
            return head
        res.next=head#构建环形链表
        pos=count-k%count-1#目标节点的前驱位置
        for i in range(pos):
            head=head.next #指向新链表的尾指针
        l=head.next# 存储头指针
        head.next=None
        return l
    

解法2:通过list直接索引

# 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:
        res=ListNode(-1)
        res.next=head
        postion=[]
        while res.next:
            res=res.next
            postion.append(res)
        count=len(postion)
        if count==0 or count==1 or k%count==0:
            return head
        res.next=head#环形
        pos=count-k%count#目标节点的位置
        postion[pos-1].next=None
        return postion[pos]

解法3:双指针,快慢指针

# 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:
        res=ListNode(-1)
        res.next=head
        first=second=head
        count=0
        while res.next:
            res=res.next
            count=count+1
        if count==0 or count==1 or k%count==0:
            return head
        for i in range(k%count):
            first=first.next
        while first.next:
            first=first.next #循环结束first指向最后一个节点
            second=second.next #second指向旋转后链表的最后一个节点
        first.next=head #构建环形链表
        head=second.next #记录头指针
        second.next=None
        return head

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值