给你一个链表的头节点 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()
欢迎在评论区留言给博主留下意见和建议,当然最重要的是,自己动手试试吧,你会做的更好