Python 旋转链表(链表)

给你一个链表的头节点 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]

算法逻辑

一般的链表是线性的,从头到尾且头尾不项链,在这到题中,我们只需建立一个能随时链接并且断开的环形链表即可

代码实现

举例:list  = 1 -> 2 ->3 -> 4 -> 5

若旋转后的链表为 5 -> 1 -> 2 ->3 -> 4

则可以将其理解为链表头尾相连并且断开了4->5的指针,此时5变成了表头,而4变成了表尾

    def rotate(self,num):
        if self.head is None or self.head.next is None:
            return
        else:
            for i in range(num):
                current = self.head
                while current.next.next:
                    current = current.next
                last_node = current.next  # 最后一个节点
                current.next = None  # 指向最后一个节点的指针被清空
                last_node.next = self.head  # 最后一个节点的下一个节点为头节点
                self.head = last_node  # 最后一个节点为头节点

完整代码

rotate(num)函数时间复杂度为O(n)

class node:
    def __init__(self,data):
        self.data = data
        self.next = None
class linked_list:
    def __init__(self):
        self.head = None
    def insert(self,data):
        new_node = node(data)
        if self.head == None:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node
    def display(self):
        if self.head == None:
            return
        else:
            current = self.head
            while current.next:
                print(current.data,end = "->")
                current = current.next
            print(current.data,"\n")

    def rotate(self,num):
        if self.head is None or self.head.next is None:
            return
        else:
            for i in range(num):
                current = self.head
                while current.next.next:
                    current = current.next
                last_node = current.next  # 最后一个节点
                current.next = None  # 指向最后一个节点的指针被清空
                last_node.next = self.head  # 最后一个节点的下一个节点为头节点
                self.head = last_node  # 最后一个节点为头节点

list = linked_list()
list.insert(1)
list.insert(2)
list.insert(3)
list.insert(4)
list.insert(5)
list.rotate(2)
list.display()

欢迎在评论区留言给博主留下意见和建议,当然最重要的是,自己动手试试吧,你会做的更好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值