题目: 旋转链表
思路:
1.首先获取链表的长度,判断旋转次数k和长度的关系,得到实际旋转次数 k = m o d ( k , l e n g t h ) k = mod(k,length) k=mod(k,length)。
2.对链表执行k次往右移动一次的 *** 作。
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if head == None or head.next ==None:
return head
length = self.get_length(head)
# 移动length次,等于不变
k = k % length
for i in range(k):
head = self.rotate1Right(head)
return head
# 链表往右移动一次
def rotate1Right(self, head):
result = ListNode()
cur = result
# 循环到倒数第二个结点
while head.next != None:
cur.next = ListNode()
cur = cur.next
cur.val = head.val
head = head.next
# 最后一个节点的值赋给头结点
result.val = head.val
return result
# 获取链表的长度
def get_length(self,head):
count = 0
while head != None:
count = count+1
head =head.next
return count
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)